output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
This function normalizes the running quantiles in a running process.
Can you tell what is the following Python 3 function doing def _cont_norm_running_quantile_mp(wl, fluxes, ivars, q, delta_lambda, n_proc=2, verbose=False): """ The same as _cont_norm_running_quantile() above, but using multi-processing. Bo Zhang (NAOC) """ nSt...
As a Python code composer, you craft elegant and concise scripts.
def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks """ print("contnorm.py: continuum norm using running quantile") pri...
Write a Python 3 function that can perform continuum normalization using running quantile
You are a Python code analyst, evaluating scripts for potential improvements.
def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda, ranges, n_proc=2, verbose=False): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks. The same as _cont_norm_running_quantile_regions(), ...
How would you code a function in Python 3 to perform continuum normalization using running quantile for spectrum
As a Python code analyst, you investigate and solve complex coding mysteries
def _cont_norm_regions(fluxes, ivars, cont, ranges): """ Perform continuum normalization for spectra in chunks Useful for spectra that have gaps Parameters --------- fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes cont: num...
How would you implement a function in Python 3 that performs continuum normalization for spectra in chunks
As a Python code composer, you craft elegant and concise scripts.
def train(self, ds): """ Run training step: solve for best-fit spectral model """ if self.useErrors: self.coeffs, self.scatters, self.new_tr_labels, self.chisqs, self.pivots, self.scales = _train_model_new(ds) else: self.coeffs, self.scatters, self.chisqs, self.pivots, se...
Implement a Python 3 function for training the spectral model on the data set.
As a Python code translator, you convert algorithms and pseudocode into Python.
Infer the model spectra for the object holding the test set.
Make a summary of the following Python 3 code def infer_spectra(self, ds): lvec_all = _get_lvec(ds.test_label_vals, self.pivots, self.scales, derivs=False) self.model_spectra = np.dot(lvec_all, self.coeffs.T)
You are a Python code architect, reviewing and designing scalable and efficient code
Plot baseline spec with continuum pix overlaid
How would you explain what the following Python 3 function does def plot_contpix(self, x, y, contpix_x, contpix_y, figname): fig, axarr = plt.subplots(2, sharex=True) plt.xlabel(r"Wavelength $\lambda (\AA)$") plt.xlim(min(x), max(x)) ax = axarr[0] ax.step(x, y, where='mid', c='k'...
As a python code expert, you are capable of creating scripts from specifications.
def diagnostics_contpix(self, data, nchunks=10, fig = "baseline_spec_with_cont_pix"): """ Call plot_contpix once for each nth of the spectrum """ if data.contmask is None: print("No contmask set") else: coeffs_all = self.coeffs wl = data.wl baselin...
How would you code a function in Python 3 to call plot_contpix once for each nth of the spectrum
You are a Python code analyst, evaluating scripts for potential improvements.
def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"): """ Produce a set of diagnostic plots for the model Parameters ---------- (optional) chisq_dist_plot_name: str Filename of output saved plot """ label_names = ds.get_plotting_labels() ...
Can you create a Python 3 function that produces a set of diagnostic plots for the model
You are a Python code architect, reviewing and designing scalable and efficient code
Calculate the mass of a node based on the given nu_max delta_nu and teff.
How would you explain what the following Python 3 function does def calc_mass(nu_max, delta_nu, teff): NU_MAX = 3140.0 # microHz DELTA_NU = 135.03 # microHz TEFF = 5777.0 return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates mass of mass 2 from mass 1 and mass 2 and mass 3.
Here you have a function in Python 3, explain what it does def calc_mass_2(mh,cm,nm,teff,logg): CplusN = calc_sum(mh,cm,nm) t = teff/4000. return (95.8689 - 10.4042*mh - 0.7266*mh**2 + 41.3642*cm - 5.3242*cm*mh - 46.7792*cm**2 + 15.0508*nm - 0.9342*nm*mh - 30.5159*nm*cm - 1.6083*nm**...
As a Python code analyst, you investigate and solve complex coding mysteries
A simple corner plot showing the projections of a data set in a multi - dimensional space.
Explain what the following Python 3 code does def corner(xs, bins=20, range=None, weights=None, color="k", smooth=None, smooth1d=None, labels=None, label_kwargs=None, show_titles=False, title_fmt=".2f", title_kwargs=None, truths=None, truth_color="#4682b4", scale_h...
You are a Python code architect, reviewing and designing scalable and efficient code
def quantile(x, q, weights=None): """ Like numpy.percentile, but: * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.] * scalar q not supported (q must be iterable) * optional weights on x """ if weights is None: return np.percentile(x, [100. * qi for qi in q]) ...
Implement a function in Python 3 to like np. percentile but returns a list of the n - th quantile of the elements in x.
You are a Python code architect, reviewing and designing scalable and efficient code
def hist2d(x, y, bins=20, range=None, weights=None, levels=None, smooth=None, ax=None, color=None, plot_datapoints=True, plot_density=True, plot_contours=True, no_fill_contours=False, fill_contours=False, contour_kwargs=None, contourf_kwargs=None, data_kwargs=None, **kwargs):...
Implement a Python 3 function for plotting a 2 - D histogram of samples.
You are a Python code generator, capable of creating scripts from specifications.
Enregistro un clasificador SVM sobre los textos cargados.
How would you explain what the following Python 3 function does def make_classifier(self, name, ids, labels): if not all(np.in1d(ids, self.ids)): raise ValueError("Hay ids de textos que no se encuentran \ almacenados.") setattr(self, name, SGDClassifier()) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Usar un clasificador SVM para etiquetar textos nuevos.
Can you tell what is the following Python 3 function doing def classify(self, classifier_name, examples, max_labels=None, goodness_of_fit=False): """Usar un clasificador SVM para etiquetar textos nuevos. Args: classifier_name (str): Nombre del clasidicador a usar. ...
You are a Python code generator, capable of creating scripts from specifications.
Return a list of similares to the given texto.
Make a summary of the following Python 3 code def get_similar(self, example, max_similars=3, similarity_cutoff=None, term_diff_max_rank=10, filter_list=None, term_diff_cutoff=None): """Devuelve textos similares al ejemplo dentro de los textos entrenados. Nota: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Re - defines the term_mat and vocabulary of the terminos de textos.
Can you generate a brief explanation for the following Python 3 code def reload_texts(self, texts, ids, vocabulary=None): self._check_id_length(ids) self.ids = np.array(sorted(ids)) if vocabulary: self.vectorizer.vocabulary = vocabulary sorted_texts = [x for (y, x) in sorted(...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get details on a GBIF dataset.
Explain what the following Python 3 code does def dataset_metrics(uuid, **kwargs): ''' Get details on a GBIF dataset. :param uuid: [str] One or more dataset UUIDs. See examples. References: http://www.gbif.org/developer/registry#datasetMetrics Usage:: from pygbif import registry registry.dataset_metrics(...
You are a Python code architect, reviewing and designing scalable and efficient code
def datasets(data = 'all', type = None, uuid = None, query = None, id = None, limit = 100, offset = None, **kwargs): ''' Search for datasets and dataset metadata. :param data: [str] The type of data to get. Default: ``all`` :param type: [str] Type of dataset, options include ``OCCURRENCE``, etc. :param uui...
How would you implement a function in Python 3 that searches for datasets and dataset metadata.
As a Python code composer, you craft elegant and concise scripts.
A simple text search that returns up to 20 matching datasets.
Make a summary of the following Python 3 code def dataset_suggest(q=None, type=None, keyword=None, owningOrg=None, publishingOrg=None, hostingOrg=None, publishingCountry=None, decade=None, limit = 100, offset = None, **kwargs): ''' Search that returns up to 20 matching datasets. Results are ordered by relevance. ...
You are a Python code generator, capable of creating scripts from specifications.
Search for datasets in the current language.
Can you generate the documentation for the following Python 3 function def dataset_search(q=None, type=None, keyword=None, owningOrg=None, publishingOrg=None, hostingOrg=None, decade=None, publishingCountry = None, facet = None, facetMincount=None, facetMultiselect = None, hl = False, limit = 100, offset = None, **...
You are a Python code analyst, evaluating scripts for potential improvements.
rewinds the WKT string x to the nearest digit
Can you tell what is the following Python 3 function doing def wkt_rewind(x, digits = None): ''' reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a sequence of occurrence issue definitions and short codes for the given issue and short code.
Can you tell what is the following Python 3 function doing def occ_issues_lookup(issue=None, code=None): ''' Lookup occurrence issue definitions and short codes :param issue: Full name of issue, e.g, CONTINENT_COUNTRY_MISMATCH :param code: an issue short code, e.g. ccm Usage pygbif.occ_issues_...
You are a Python code generator, capable of creating scripts from specifications.
def search(taxonKey=None, repatriated=None, kingdomKey=None, phylumKey=None, classKey=None, orderKey=None, familyKey=None, genusKey=None, subgenusKey=None, scientificName=None, country=None, publishingCountry=None, hasCoordinate=None, typeStatus=None, recordNumber=None, lastInterpreted=None, continent=N...
Implement a function in Python 3 to search GBIF occurrences in a specific GBIF file.
As a python code expert, you are capable of creating scripts from specifications.
Get a dictionary of network metadata.
Make a summary of the following Python 3 code def networks(data = 'all', uuid = None, q = None, identifier = None, identifierType = None, limit = 100, offset = None, **kwargs): ''' Networks metadata. Note: there's only 1 network now, so there's not a lot you can do with this method. :param data: [str] The t...
As a Python code analyst, you investigate and solve complex coding mysteries
def map(source = 'density', z = 0, x = 0, y = 0, format = '@1x.png', srs='EPSG:4326', bin=None, hexPerTile=None, style='classic.point', taxonKey=None, country=None, publishingCountry=None, publisher=None, datasetKey=None, year=None, basisOfRecord=None, **kwargs): ''' GBIF maps API :param sou...
Can you write a function in Python 3 where it returns a GBIF map for the specified source.
As a python code expert, you are capable of creating scripts from specifications.
check if a variable is present in the environmental variables
Make a summary of the following Python 3 code def _check_environ(variable, value): if is_not_none(value): return value else: value = os.environ.get(variable) if is_none(value): stop(''.join([variable, """ not supplied and no entry in environmental ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function is used to kick up a download job for a GBIF occurrence data.
Make a summary of the following Python 3 code def download(queries, user=None, pwd=None, email=None, pred_type='and'): """ Spin up a download request for GBIF occurrence data. :param queries: One or more of query arguments to kick of a download job. See Details. :type queries: str ...
As a Python code composer, you craft elegant and concise scripts.
Lists the downloads created by a user.
Make a summary of the following Python 3 code def download_list(user=None, pwd=None, limit=20, offset=0): user = _check_environ('GBIF_USER', user) pwd = _check_environ('GBIF_PWD', pwd) url = 'http://api.gbif.org/v1/occurrence/download/user/' + user args = {'limit': limit, 'offset': offset} res = g...
As a python code expert, you are capable of creating scripts from specifications.
Download a file from GBIF.
Make a summary of the following Python 3 code def download_get(key, path=".", **kwargs): meta = pygbif.occurrences.download_meta(key) if meta['status'] != 'SUCCEEDED': raise Exception('download "%s" not of status SUCCEEDED' % key) else: print('Download file size: %s bytes' % meta['size']) ...
You are a Python code analyst, evaluating scripts for potential improvements.
set main predicate combination type
How would you explain what the following Python 3 function does def main_pred_type(self, value): if value not in operators: value = operator_lkup.get(value) if value: self._main_pred_type = value self.payload['predicate']['type'] = self._main_pred_type else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_predicate(self, key, value, predicate_type='equals'): """ add key, value, type combination of a predicate :param key: query KEY parameter :param value: the value used in the predicate :param predicate_type: the type of predicate (e.g. ``equals``) """ if p...
Can you write a function in Python 3 where it adds predicate to the list of predicates
As a python code expert, you are capable of creating scripts from specifications.
def _extract_values(values_list): """extract values from either file or list :param values_list: list or file name (str) with list of values """ values = [] # check if file or list of values to iterate if isinstance(values_list, str): with open(values_list) a...
Create a Python 3 function to extract values from either file or list of values
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_iterative_predicate(self, key, values_list): """add an iterative predicate with a key and set of values which it can be equal to in and or function. The individual predicates are specified with the type ``equals`` and combined with a type ``or``. The main reason for this...
How would you code a function in Python 3 to add an iterative predicate with a key and set of values_list which it can be equal to in and or function.
You are a Python code architect, reviewing and designing scalable and efficient code
def get(key, **kwargs): ''' Gets details for a single, interpreted occurrence :param key: [int] A GBIF occurrence key :return: A dictionary, of results Usage:: from pygbif import occurrences occurrences.get(key = 1258202889) occurrences.get(key = 1227768771) occur...
Write a Python 3 function for getting details for a single interpreted occurrence
You are a Python code architect, reviewing and designing scalable and efficient code
def get_verbatim(key, **kwargs): ''' Gets a verbatim occurrence record without any interpretation :param key: [int] A GBIF occurrence key :return: A dictionary, of results Usage:: from pygbif import occurrences occurrences.get_verbatim(key = 1258202889) occurrences.get_ve...
Write a Python 3 function for getting a verbatim occurrence record without any interpretation
You are a Python code generator, capable of creating scripts from specifications.
Get a single occurrence fragment in its raw form.
Given the following Python 3 function, write the documentation def get_fragment(key, **kwargs): ''' Get a single occurrence fragment in its raw form (xml or json) :param key: [int] A GBIF occurrence key :return: A dictionary, of results Usage:: from pygbif import occurrences occu...
You are a Python code architect, reviewing and designing scalable and efficient code
def name_parser(name, **kwargs): ''' Parse taxon names using the GBIF name parser :param name: [str] A character vector of scientific names. (required) reference: http://www.gbif.org/developer/species#parser Usage:: from pygbif import species species.name_parser('x Agropogon littoralis') ...
Write a Python 3 script for parsing taxon names using the GBIF name parser.
As a Python code composer, you craft elegant and concise scripts.
This function is used to perform a fuzzy name lookup on a set of terms.
How would you explain what the following Python 3 function does def name_lookup(q=None, rank=None, higherTaxonKey=None, status=None, isExtinct=None, habitat=None, nameType=None, datasetKey=None, nomenclaturalStatus=None, limit=100, offset=None, facet=False, facetMincount=None, facetMultiselect=None, type=None, hl=Fa...
As a python code expert, you are capable of creating scripts from specifications.
def count(taxonKey=None, basisOfRecord=None, country=None, isGeoreferenced=None, datasetKey=None, publishingCountry=None, typeStatus=None, issue=None, year=None, **kwargs): ''' Returns occurrence counts for a predefined set of dimensions :param taxonKey: [int] A GBIF occurrence identifier :para...
Can you implement a function in Python 3 that returns occurrence counts for a predefined set of dimensions of a predefined set of dimensions of a GBIF occurrence identifier.
As a Python code analyst, you investigate and solve complex coding mysteries
Lists occurrence counts by year
Can you generate the documentation for the following Python 3 function def count_year(year, **kwargs): ''' Lists occurrence counts by year :param year: [int] year range, e.g., ``1990,2000``. Does not support ranges like ``asterisk,2010`` :return: dict Usage:: from pygbif import occur...
You are a Python code analyst, evaluating scripts for potential improvements.
def count_datasets(taxonKey = None, country = None, **kwargs): ''' Lists occurrence counts for datasets that cover a given taxon or country :param taxonKey: [int] Taxon key :param country: [str] A country, two letter code :return: dict Usage:: from pygbif import occurrences ...
Create a Python 3 function to return a dictionary of occurrence counts for datasets that cover a given taxon or country.
You are a Python code architect, reviewing and designing scalable and efficient code
def count_countries(publishingCountry, **kwargs): ''' Lists occurrence counts for all countries covered by the data published by the given country :param publishingCountry: [str] A two letter country code :return: dict Usage:: from pygbif import occurrences occurrences.co...
Create a Python 3 function for returning a dictionary containing the occurrence counts for all countries covered by the data published by the given country.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dictionary of occurrence counts for all countries that publish data about the given country.
Here you have a function in Python 3, explain what it does def count_publishingcountries(country, **kwargs): ''' Lists occurrence counts for all countries that publish data about the given country :param country: [str] A country, two letter code :return: dict Usage:: from pygbif impo...
As a Python code composer, you craft elegant and concise scripts.
Detect if code is running in a Jupyter Notebook.
Given the following Python 3 function, write the documentation def _detect_notebook() -> bool: try: from IPython import get_ipython from ipykernel import zmqshell except ImportError: return False kernel = get_ipython() try: from spyder.utils.ipython.spyder_kernel import S...
You are a Python code architect, reviewing and designing scalable and efficient code
Merge attributes from two layouts.
Given the following Python 3 function, write the documentation def _merge_layout(x: go.Layout, y: go.Layout) -> go.Layout: xjson = x.to_plotly_json() yjson = y.to_plotly_json() if 'shapes' in yjson and 'shapes' in xjson: xjson['shapes'] += yjson['shapes'] yjson.update(xjson) return go.Layout...
As a python code expert, you are capable of creating scripts from specifications.
def _try_pydatetime(x): """Try to convert to pandas objects to datetimes. Plotly doesn't know how to handle them. """ try: # for datetimeindex x = [y.isoformat() for y in x.to_pydatetime()] except AttributeError: pass try: # for generic series x = [y.isof...
Can you write a function in Python 3 where it tries to convert to pandas objects to datetimes.
As a Python code composer, you craft elegant and concise scripts.
def spark_shape(points, shapes, fill=None, color='blue', width=5, yindex=0, heights=None): """TODO: Docstring for spark. Parameters ---------- points : array-like shapes : array-like fill : array-like, optional Returns ------- Chart """ assert len(points) == len(shapes) + ...
Create a Python 3 function for returning a spark chart with the specified shape.
As a Python code composer, you craft elegant and concise scripts.
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None): """Draws a vertical line from `ymin` to `ymax`. Parameters ---------- xmin : int, optional xmax : int, optional color : str, optional width : number, optional Returns ------- Chart """ li...
Create a Python 3 function to draw a vertical line from xmin xmax color dash opacity opacity
As a Python code analyst, you investigate and solve complex coding mysteries
def horizontal(y, xmin=0, xmax=1, color=None, width=None, dash=None, opacity=None): """Draws a horizontal line from `xmin` to `xmax`. Parameters ---------- xmin : int, optional xmax : int, optional color : str, optional width : number, optional Returns ------- Chart """ ...
Can you implement a function in Python 3 that draws a horizontal line from xmin to xmax.
As a Python code composer, you craft elegant and concise scripts.
Draws connected dots. Parameters ---------- x : array-like, optional y : array-like, optional label : array-like, optional Returns ------- Chart
Can you generate the documentation for the following Python 3 function def line( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', yaxis=1, fill=None, text="", markersize=6, ): """Draws connected dots. Parameters ...
You are a Python code analyst, evaluating scripts for potential improvements.
def line3d( x, y, z, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers' ): """Create a 3d line chart.""" x = np.atleast_1d(x) y = np.atleast_1d(y) z = np.atleast_1d(z) assert x.shape == y.shape assert y.shape == z.shape lineattr = {} if color: l...
Create a Python 3 function for creating a 3d line chart.
As a Python code composer, you craft elegant and concise scripts.
def scatter( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, markersize=6, yaxis=1, fill=None, text="", mode='markers', ): """Draws dots. Parameters ---------- x : array-like, optional y : array-like, optional label : ...
How would you code a function in Python 3 to draw dots. Parameters ---------- x : array-like, optional y : array-like, optional label : array-like, optional Returns ------- Chart
As a Python code analyst, you investigate and solve complex coding mysteries
def bar(x=None, y=None, label=None, mode='group', yaxis=1, opacity=None): """Create a bar chart. Parameters ---------- x : array-like, optional y : TODO, optional label : TODO, optional mode : 'group' or 'stack', default 'group' opacity : TODO, optional Returns ------- Char...
Write a Python 3 function that can create a bar chart.
As a Python code composer, you craft elegant and concise scripts.
def heatmap(z, x=None, y=None, colorscale='Viridis'): """Create a heatmap. Parameters ---------- z : TODO x : TODO, optional y : TODO, optional colorscale : TODO, optional Returns ------- Chart """ z = np.atleast_1d(z) data = [go.Heatmap(z=z, x=x, y=y, colorscale=...
Write a Python 3 function for creating a heatmap. Parameters ---------- z : TODO x : TODO, optional y : TODO, optional colorscale : TODO, optional Returns ------- Chart
You are a Python code generator, capable of creating scripts from specifications.
Fill to zero. Parameters ---------- x : array-like, optional y : TODO, optional label : TODO, optional Returns ------- Chart
Can you tell what is the following Python 3 function doing def fill_zero( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', **kargs ): """Fill to zero. Parameters ---------- x : array-like, optional y : TODO, optio...
You are a Python code architect, reviewing and designing scalable and efficient code
Fill between ylow and yhigh.
How would you explain what the following Python 3 function does def fill_between( x=None, ylow=None, yhigh=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', **kargs ): """Fill between `ylow` and `yhigh`. Parameters ---------- ...
As a Python code composer, you craft elegant and concise scripts.
def rug(x, label=None, opacity=None): """Rug chart. Parameters ---------- x : array-like, optional label : TODO, optional opacity : TODO, optional Returns ------- Chart """ x = _try_pydatetime(x) x = np.atleast_1d(x) data = [ go.Scatter( x=x, ...
Create a Python 3 function to return a chart that shows the rug of the object.
You are a Python code analyst, evaluating scripts for potential improvements.
def surface(x, y, z): """Surface plot. Parameters ---------- x : array-like, optional y : array-like, optional z : array-like, optional Returns ------- Chart """ data = [go.Surface(x=x, y=y, z=z)] return Chart(data=data)
Implement a Python 3 function for surfacing plot. Parameters ---------- x : array-like, optional y : array-like, optional z : array-like, optional Returns ------- Chart
You are a Python code architect, reviewing and designing scalable and efficient code
def hist(x, mode='overlay', label=None, opacity=None, horz=False, histnorm=None): """Histogram. Parameters ---------- x : array-like mode : str, optional label : TODO, optional opacity : float, optional horz : bool, optional histnorm : None, "percent", "probability", "density", "pro...
Write a Python 3 function for returning a chart that contains a histogram of the data points x.
As a Python code analyst, you investigate and solve complex coding mysteries
Set the angle of the y - axis tick labels.
Explain what the following Python 3 code does def ytickangle(self, angle, index=1): self.layout['yaxis' + str(index)]['tickangle'] = angle return self
You are a Python code analyst, evaluating scripts for potential improvements.
def ylabelsize(self, size, index=1): """Set the size of the label. Parameters ---------- size : int Returns ------- Chart """ self.layout['yaxis' + str(index)]['titlefont']['size'] = size return self
Write a Python 3 function for setting the size of the label.
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the tick font size.
Given the following Python 3 function, write the documentation def yticksize(self, size, index=1): self.layout['yaxis' + str(index)]['tickfont']['size'] = size return self
You are a Python code analyst, evaluating scripts for potential improvements.
def ytickvals(self, values, index=1): """Set the tick values. Parameters ---------- values : array-like Returns ------- Chart """ self.layout['yaxis' + str(index)]['tickvals'] = values return self
Can you create a Python 3 function that sets the tick values.
You are a Python code generator, capable of creating scripts from specifications.
Set the tick labels.
Can you tell what is the following Python 3 function doing def yticktext(self, labels, index=1): self.layout['yaxis' + str(index)]['ticktext'] = labels return self
You are a Python code generator, capable of creating scripts from specifications.
Set yaxis limits. Parameters ---------- low : number high : number index : int, optional Returns ------- Chart
Can you generate the documentation for the following Python 3 function def ylim(self, low, high, index=1): self.layout['yaxis' + str(index)]['range'] = [low, high] return self
As a Python code translator, you convert algorithms and pseudocode into Python.
def ydtick(self, dtick, index=1): """Set the tick distance.""" self.layout['yaxis' + str(index)]['dtick'] = dtick return self
Write a Python 3 function for setting the tick distance.
You are a Python code generator, capable of creating scripts from specifications.
Set the number of ticks.
Here you have a function in Python 3, explain what it does def ynticks(self, nticks, index=1): self.layout['yaxis' + str(index)]['nticks'] = nticks return self
As a Python code analyst, you investigate and solve complex coding mysteries
Display the chart. Parameters ---------- filename : str, optional Save plot to this filename, otherwise it's saved to a temporary file. show_link : bool, optional Show link to plotly. auto_open : bool, optional Automatically open the plot (in ...
Can you tell what is the following Python 3 function doing def show( self, filename: Optional[str] = None, show_link: bool = True, auto_open: bool = True, detect_notebook: bool = True, ) -> None: """Display the chart. Parameters ---------- fil...
As a Python code analyst, you investigate and solve complex coding mysteries
def save( self, filename: Optional[str] = None, show_link: bool = True, auto_open: bool = False, output: str = 'file', plotlyjs: bool = True, ) -> str: """Save the chart to an html file.""" if filename is None: filename = NamedTemporaryFile...
How would you implement a function in Python 3 that saves the chart to an html file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Register a method in the class.
Can you generate a brief explanation for the following Python 3 code def RegisterMethod(cls, *args, **kwargs): unpack_error = True try: f, library_path = args unpack_error = False cls._RegisterMethod(f, library_path, **kwargs) except: if not unpa...
You are a Python code generator, capable of creating scripts from specifications.
**RegisterAt** RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None) Most of the time you don't want to register an method as such, that is, you don't care about the `self` builder object, instead you wan...
How would you explain what the following Python 3 function does def RegisterAt(cls, *args, **kwargs): unpack_error = True try: n, f, library_path = args unpack_error = False cls._RegisterAt(n, f, library_path, **kwargs) except: if not unpack_erro...
You are a Python code analyst, evaluating scripts for potential improvements.
This classmethod allows you to patch all of functions or methods at a specific position.
Can you generate a brief explanation for the following Python 3 code def PatchAt(cls, n, module, method_wrapper=None, module_alias=None, method_name_modifier=utils.identity, blacklist_predicate=_False, whitelist_predicate=_True, return_type_predicate=_None, getmembers_predicate=inspect.isfunction, admit_private=False, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_method_sig(method): """ Given a function, it returns a string that pretty much looks how the function signature_ would be written in python. :param method: a python method :return: A string similar describing the pythong method signature_. eg: "my_method(first_argArg, second_arg=42, third_a...
Can you create a Python 3 function that gives a function it returns a string that pretty much looks how the method signature_ would be written in python.
As a Python code translator, you convert algorithms and pseudocode into Python.
A function that takes a single argument and returns a partial that expects a single argument at the given position.
How would you explain what the following Python 3 function does def ThenAt(self, n, f, *_args, **kwargs): _return_type = None n_args = n - 1 if '_return_type' in kwargs: _return_type = kwargs['_return_type'] del kwargs['_return_type'] @utils.lift def g(x...
You are a Python code generator, capable of creating scripts from specifications.
A second order then function.
Given the following Python 3 function, write the documentation def Then(self, f, *args, **kwargs): return self.ThenAt(1, f, *args, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
A second order then 5 function.
Can you generate a brief explanation for the following Python 3 code def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs): args = (arg1, arg2, arg3, arg4) + args return self.ThenAt(5, f, *args, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def List(self, *branches, **kwargs): """ While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) tha...
Implement a function in Python 3 to while `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) that is not a tu...
You are a Python code generator, capable of creating scripts from specifications.
def Seq(self, *sequence, **kwargs): """ `Seq` is used to express function composition. The expression Seq(f, g) be equivalent to lambda x: g(f(x)) As you see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about cod...
Can you write a function in Python 3 where it returns a new sequence that is the sequence of the given elements.
As a python code expert, you are capable of creating scripts from specifications.
A simple context manager with a given DSL.
Explain what the following Python 3 code does def With(self, context_manager, *body, **kwargs): context_f = _parse(context_manager)._f body_f = E.Seq(*body)._f def g(x, state): context, state = context_f(x, state) with context as scope: with _WithContextM...
As a Python code composer, you craft elegant and concise scripts.
A version of phi. dsl. Expression. List that handles the case where a string argument x is translated to Read.
Explain what the following Python 3 code does def ReadList(self, *branches, **kwargs): branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, branches) return self.List(*branches, **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
See phi. dsl. Expression. Write
Here you have a function in Python 3, explain what it does def Write(self, *state_args, **state_dict): if len(state_dict) + len(state_args) < 1: raise Exception("Please include at-least 1 state variable, got {0} and {1}".format(state_args, state_dict)) if len(state_dict) > 1: ra...
As a Python code translator, you convert algorithms and pseudocode into Python.
def Val(self, val, **kwargs): """ The expression Val(a) is equivalent to the constant function lambda x: a All expression in this module interprete values that are not functions as constant functions using `Val`, for example Seq(1, P + 1) is equivalent to Seq(Val(1), P + 1) The previous ...
Write a Python 3 script to return a new Seq with the given value.
As a python code expert, you are capable of creating scripts from specifications.
See phi. dsl. Expression. If
How would you explain what the following Python 3 function does def Else(self, *Else, **kwargs): root = self._root ast = self._ast next_else = E.Seq(*Else)._f ast = _add_else(ast, next_else) g = _compile_if(ast) return root.__then__(g, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the length of the string.
Can you generate a brief explanation for the following Python 3 code def length(string, until=None): if until is None: return sum(1 for _ in GraphemeIterator(string)) iterator = graphemes(string) count = 0 while True: try: if count >= until: break ...
As a Python code composer, you craft elegant and concise scripts.
Returns a substring of the given string counting graphemes instead of codepoints.
Can you generate the documentation for the following Python 3 function def slice(string, start=None, end=None): if start is None: start = 0 if end is not None and start >= end: return "" if start < 0: raise NotImplementedError("Negative indexing is currently not supported.") s...
You are a Python code generator, capable of creating scripts from specifications.
def contains(string, substring): """ Returns true if the sequence of graphemes in substring is also present in string. This differs from the normal python `in` operator, since the python operator will return true if the sequence of codepoints are withing the other string without considering graphem...
Implement a function in Python 3 to return True if the grapheme sequence of graphemes in substring is also present in string.
As a python code expert, you are capable of creating scripts from specifications.
def startswith(string, prefix): """ Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes. str.startswith may return true for a prefix that is not visually represented as a prefix if a grapheme cluster is continued after the prefix ends. >>> grap...
How would you code a function in Python 3 to like str. startswith but checks that the given string starts with the given prefixes sequence of graphemes.
As a Python code analyst, you investigate and solve complex coding mysteries
Like str. endswith but checks that the given string ends with the given suffix.
Can you tell what is the following Python 3 function doing def endswith(string, suffix): expected_index = len(string) - len(suffix) return string.endswith(suffix) and safe_split_index(string, expected_index) == expected_index
You are a Python code generator, capable of creating scripts from specifications.
def safe_split_index(string, max_len): """ Returns the highest index up to `max_len` at which the given string can be sliced, without breaking a grapheme. This is useful for when you want to split or take a substring from a string, and don't really care about the exact grapheme length, but don't want t...
Can you create a Python 3 function that returns the highest index up to `max_len` at which the given string can be sliced, without breaking a grapheme. This is useful for when you want to split or take a substring from a string, and don't really care about the exact grapheme length, but don't want to risk breaking exis...
You are a Python code architect, reviewing and designing scalable and efficient code
Read the B1 logfile and return a dictionary.
Can you generate a brief explanation for the following Python 3 code def readB1logfile(filename): dic = dict() # try to open. If this fails, an exception is raised with open(filename, 'rt', encoding='utf-8') as f: for l in f: l = l.strip() if l[0] in '#!%\'': ...
You are a Python code architect, reviewing and designing scalable and efficient code
Write a header structure into a B1 logfile.
Given the following Python 3 function, write the documentation def writeB1logfile(filename, data): allkeys = list(data.keys()) f = open(filename, 'wt', encoding='utf-8') for ld in _logfile_data: # process each line linebegin = ld[0] fieldnames = ld[1] # set the default formatter if ...
As a Python code composer, you craft elegant and concise scripts.
def readB1header(filename): """Read beamline B1 (HASYLAB, Hamburg) header data Input ----- filename: string the file name. If ends with ``.gz``, it is fed through a ``gunzip`` filter Output ------ A header dictionary. Examples -------- read header data from 'OR...
Can you implement a function in Python 3 that reads beamline B1 header data from file.
As a Python code composer, you craft elegant and concise scripts.
Read the EDF header from a file and return a dictionary of the EDF header structure.
Can you generate the documentation for the following Python 3 function def readehf(filename): f = open(filename, 'r') edf = {} if not f.readline().strip().startswith('{'): raise ValueError('Invalid file format.') for l in f: l = l.strip() if not l: continue if...
As a python code expert, you are capable of creating scripts from specifications.
def readbhfv1(filename, load_data=False, bdfext='.bdf', bhfext='.bhf'): """Read header data from bdf/bhf file (Bessy Data Format v1) Input: filename: the name of the file load_data: if the matrices are to be loaded Output: bdf: the BDF header structure Adapted the bdf_read.m m...
Write a Python 3 script for reading the header data from a Bessy Data Format v1 file.
You are a Python code analyst, evaluating scripts for potential improvements.
Read a header from a MarResearch. image file.
Can you generate a brief explanation for the following Python 3 code def readmarheader(filename): with open(filename, 'rb') as f: intheader = np.fromstring(f.read(10 * 4), np.int32) floatheader = np.fromstring(f.read(15 * 4), '<f4') strheader = f.read(24) f.read(4) otherstrin...
As a Python code translator, you convert algorithms and pseudocode into Python.
Read a header from a BerSANS file.
Can you generate the documentation for the following Python 3 function def readBerSANS(filename): hed = {'Comment': ''} translate = {'Lambda': 'Wavelength', 'Title': 'Owner', 'SampleName': 'Title', 'BeamcenterX': 'BeamPosY', 'BeamcenterY': 'Bea...
As a Python code analyst, you investigate and solve complex coding mysteries
Cosine function for frequency - based variables.
Make a summary of the following Python 3 code def Cosine(x, a, omega, phi, y0): return a * np.cos(x * omega + phi) + y0
You are a Python code architect, reviewing and designing scalable and efficient code
def Square(x, a, b, c): """Second order polynomial Inputs: ------- ``x``: independent variable ``a``: coefficient of the second-order term ``b``: coefficient of the first-order term ``c``: additive constant Formula: -------- ``a*x^2 + b*x + c`` """ r...
Can you implement a function in Python 3 that seconds order polynomial of a set of terms.
You are a Python code generator, capable of creating scripts from specifications.