text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_series_equal(left, right, data_function=None, data_args=None): """ For unit testing equality of two Series. :param left: first Series :param right: se...
assert type(left) == type(right) if data_function: data_args = {} if not data_args else data_args data_function(left.data, right.data, **data_args) else: assert left.data == right.data assert left.index == right.index assert left.data_name == right.data_name assert left....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, timeout=None): """Return result from the pipeline."""
result = None for stage in self._output_stages: result = stage.get(timeout) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """Load the lyrics from MetroLyrics."""
page = requests.get(self._url) # Forces utf-8 to prevent character mangling page.encoding = 'utf-8' tree = html.fromstring(page.text) lyric_div = tree.get_element_by_id('lyrics-body-text') verses = [c.text_content() for c in lyric_div.find_class('verse')] self._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, verbose=False): """ Load the list of songs. Note that this only loads a list of songs that this artist was the main artist of. If they were only f...
self._songs = [] page_num = 1 total_pages = 1 while page_num <= total_pages: if verbose: print('retrieving page %d' % page_num) page = requests.get(ARTIST_URL.format(artist=self.name, n=page_num))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(p0, p1, deg=True, r=r_earth_mean): """ Return the distance between two points on the surface of the Earth. Parameters p0 : point-like (or array of p...
single, (p0, p1) = _to_arrays((p0, 2), (p1, 2)) if deg: p0 = np.radians(p0) p1 = np.radians(p1) lon0, lat0 = p0[:,0], p0[:,1] lon1, lat1 = p1[:,0], p1[:,1] # h_x used to denote haversine(x): sin^2(x / 2) h_dlat = sin((lat1 - lat0) / 2.0) ** 2 h_dlon = sin((lon1 - lon0) / 2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def course(p0, p1, deg=True, bearing=False): """ Compute the initial bearing along the great circle from p0 to p1 NB: The angle returned by course() is not the t...
single, (p0, p1) = _to_arrays((p0, 2), (p1, 2)) if deg: p0 = np.radians(p0) p1 = np.radians(p1) lon0, lat0 = p0[:,0], p0[:,1] lon1, lat1 = p1[:,0], p1[:,1] dlon = lon1 - lon0 a = sin(dlon) * cos(lat1) b = cos(lat0) * sin(lat1) - sin(lat0) * cos(lat1) * cos(dlon) if be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean): """ Given an initial point and angle, move distance d along the surface Parameters p0 : poi...
single, (p0, angle, d) = _to_arrays((p0, 2), (angle, 1), (d, 1)) if deg: p0 = np.radians(p0) angle = np.radians(angle) if not bearing: angle = np.pi / 2.0 - angle lon0, lat0 = p0[:,0], p0[:,1] angd = d / r lat1 = arcsin(sin(lat0) * cos(angd) + cos(lat0) * sin(angd) * ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, signature, timestamp, nonce): """Validate request signature. :param signature: A string signature parameter sent by weixin. :param timestamp: ...
if not self.token: raise RuntimeError('WEIXIN_TOKEN is missing') if self.expires_in: try: timestamp = int(timestamp) except (ValueError, TypeError): # fake timestamp return False delta = time.time() - time...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, content): """Parse xml body sent by weixin. :param content: A text of xml body. """
raw = {} try: root = etree.fromstring(content) except SyntaxError as e: raise ValueError(*e.args) for child in root: raw[child.tag] = child.text formatted = self.format(raw) msg_type = formatted['type'] msg_parser = getattr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reply(self, username, type='text', sender=None, **kwargs): """Create the reply text for weixin. The reply varies per reply type. The acceptable types are `te...
sender = sender or self.sender if not sender: raise RuntimeError('WEIXIN_SENDER or sender argument is missing') if type == 'text': content = kwargs.get('content', '') return text_reply(username, sender, content) if type == 'music': value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, key=None, func=None, **kwargs): """Register a command helper function. You can register the function:: def print_help(**kwargs): username = k...
if func: if key is None: limitation = frozenset(kwargs.items()) self._registry_without_key.append((func, limitation)) else: self._registry[key] = func return func return self.__call__(key, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_func(self): """Default view function for Flask app. This is a simple implementation for view func, you can add it to your Flask app:: weixin = Weixin(ap...
if request is None: raise RuntimeError('view_func need Flask be installed') signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') if not self.validate(signature, timestamp, nonce): return 's...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self): """Reads the remote file from Gist and save it locally"""
if self.gist: content = self.github.read_gist_file(self.gist) self.local.save(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def oauth_only(function): """Decorator to restrict some GitHubTools methods to run only with OAuth"""
def check_for_oauth(self, *args, **kwargs): """ Returns False if GitHubTools instance is not authenticated, or return the decorated fucntion if it is. """ if not self.is_authenticated: self.oops("To use putgist you have to set your GETGIST_TOKEN") se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, url, params=None, **kwargs): """Encapsulte requests.get to use this class instance header"""
return requests.get(url, params=params, headers=self.add_headers(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(self, url, data=None, **kwargs): """Encapsulte requests.patch to use this class instance header"""
return requests.patch(url, data=data, headers=self.add_headers(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, url, data=None, **kwargs): """Encapsulte requests.post to use this class instance header"""
return requests.post(url, data=data, headers=self.add_headers(**kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup(self): """Backups files with the same name of the instance filename"""
count = 0 name = "{}.bkp".format(self.filename) backup = os.path.join(self.cwd, name) while os.path.exists(backup): count += 1 name = "{}.bkp{}".format(self.filename, count) backup = os.path.join(self.cwd, name) self.hey("Moving existing {} to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def char_matcher(mode): """ a faster way for characters to generate token strings cache """
def f_raw(inp_str, pos): return mode if inp_str[pos] is mode else None def f_collection(inp_str, pos): ch = inp_str[pos] for each in mode: if ch is each: return ch return None if isinstance(mode, str): return f_raw i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(self, method, resource_uri, **kwargs): """Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HT...
data = kwargs.get('data') response = method(self.API_BASE_URL + resource_uri, json=data, headers=self.headers) response.raise_for_status() return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(cls, customer_id, **kwargs): """ Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: cu...
return cls().requests.put('customer/{customer_id}'.format(**locals()), data=kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(txt): """ Accepts Slack formatted text and returns HTML. """
# Removing links to other channels txt = re.sub(r'<#[^\|]*\|(.*)>', r'#\g<1>', txt) # Removing links to other users txt = re.sub(r'<(@.*)>', r'\g<1>', txt) # handle named hyperlinks txt = re.sub(r'<([^\|]*)\|([^\|]*)>', r'<a href="\g<1>" target="blank">\g<2></a>', txt) # handle unnamed ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open_list(self, list_type): """ Add an open list tag corresponding to the specification in the parser's LIST_TYPES. """
if list_type in LIST_TYPES.keys(): tag = LIST_TYPES[list_type] else: raise Exception('CustomSlackdownHTMLParser:_open_list: Not a valid list type.') html = '<{t} class="list-container-{c}">'.format( t=tag, c=list_type ) self.clean...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _close_list(self): """ Add an close list tag corresponding to the currently open list found in current_parent_element. """
list_type = self.current_parent_element['attrs']['class'] tag = LIST_TYPES[list_type] html = '</{t}>'.format( t=tag ) self.cleaned_html += html self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_starttag(self, tag, attrs): """ Called by HTMLParser.feed when a start tag is found. """
# Parse the tag attributes attrs_dict = dict(t for t in attrs) # If the tag is a predefined parent element if tag in PARENT_ELEMENTS: # If parser is parsing another parent element if self.current_parent_element['tag'] != '': # close the parent el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """
if tag in PARENT_ELEMENTS: self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = '' if tag == 'li': self.parsing_li = True if tag != 'br': self.cleaned_html += '</{}>'.format(tag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_data(self, data): """ Called by HTMLParser.feed when text is found. """
if self.current_parent_element['tag'] == '': self.cleaned_html += '<p>' self.current_parent_element['tag'] = 'p' self.cleaned_html += data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remove_pre_formatting(self): """ Removes formatting tags added to pre elements. """
preformatted_wrappers = [ 'pre', 'code' ] for wrapper in preformatted_wrappers: for formatter in FORMATTERS: tag = FORMATTERS[formatter] character = formatter regex = r'(<{w}>.*)<{t}>(.*)</{t}>(.*</{w}>)'.form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """ Goes through the txt input and cleans up any problematic HTML. """
# Calls handle_starttag, handle_endtag, and handle_data self.feed() # Clean up any parent tags left open if self.current_parent_element['tag'] != '': self.cleaned_html += '</{}>'.format(self.current_parent_element['tag']) # Remove empty <p> added after lists ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_model(LAB_DIR): """ Cannon model params """
coeffs = np.load("%s/coeffs.npz" %LAB_DIR)['arr_0'] scatters = np.load("%s/scatters.npz" %LAB_DIR)['arr_0'] chisqs = np.load("%s/chisqs.npz" %LAB_DIR)['arr_0'] pivots = np.load("%s/pivots.npz" %LAB_DIR)['arr_0'] return coeffs, scatters, chisqs, pivots
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_normed_spectra(): """ Spectra to compare with models """
wl = np.load("%s/wl.npz" %LAB_DIR)['arr_0'] filenames = np.array( [SPEC_DIR + "/Spectra" + "/" + val for val in lamost_id]) grid, fluxes, ivars, npix, SNRs = lamost.load_spectra( lamost_id, input_grid=wl) ds = dataset.Dataset( wl, lamost_id, fluxes, ivars, [1], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wget_files(): """ Pull the files from the LAMOST archive """
for f in lamost_id: short = (f.split('-')[2]).split('_')[0] filename = "%s/%s.gz" %(short,f) DIR = "/Users/annaho/Data/Li_Giants/Spectra_APOKASC" searchfor = "%s/%s.gz" %(DIR,f) if glob.glob(searchfor): print("done") else: #print(searchfor) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cannon_normalize(spec_raw): """ Normalize according to The Cannon """
spec = np.array([spec_raw]) wl = np.arange(0, spec.shape[1]) w = continuum_normalization.gaussian_weight_matrix(wl, L=50) ivar = np.ones(spec.shape)*0.5 cont = continuum_normalization._find_cont_gaussian_smooth( wl, spec, ivar, w) norm_flux, norm_ivar = continuum_normalization._cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(grid, wl, flux): """ Resample spectrum onto desired grid """
flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_residuals(ds, m): """ Using the dataset and model object, calculate the residuals and return Parameters ds: dataset object m: model object Return ------ ...
model_spectra = get_model_spectra(ds, m) resid = ds.test_flux - model_spectra return resid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_model(): """ Load the model Parameters direc: directory with all of the model files Returns ------- m: model object """
direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn" m = model.CannonModel(2) m.coeffs = np.load(direc + "/coeffs.npz")['arr_0'][0:3626,:] # no cols m.scatters = np.load(direc + "/scatters.npz")['arr_0'][0:3626] # no cols m.chisqs = np.load(direc + "/chisqs.npz")['arr_0'][0:3626] # no cols ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """
try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(yerrs, amps, amp_errs, widths): """ criteria for keeping an object """
keep_1 = np.logical_and(amps < 0, widths > 1) keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps)) keep = np.logical_and(keep_1, keep_2) return keep
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_all(): """ Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(dates, np.where(dates=='.directory')[0][0]) dates = np.delete(dates, np.where(dates=='all_folders.list')[0][0]) dates = np.del...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_colors(catalog): """ Pull colors from catalog Parameters catalog: filename """
print("Get Colors") a = pyfits.open(catalog) data = a[1].data a.close() all_ids = data['LAMOST_ID_1'] all_ids = np.array([val.strip() for val in all_ids]) # G magnitude gmag = data['gpmag'] gmag_err = data['e_gpmag'] # R magnitude rmag = data['rpmag'] rmag_err = data['e_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters md: model The Cannon spectral model ds: Dataset Dataset object Return...
coeffs_all, covs, scatters, red_chisqs, pivots, label_vector = model.model nstars = len(dataset.test_SNR) cannon_flux = np.zeros(dataset.test_flux.shape) cannon_ivar = np.zeros(dataset.test_ivar.shape) for i in range(nstars): x = label_vector[:,i,:] spec_fit = np.einsum('ij, ij->i',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars): """ Find and return continuum pixels given the flux and sigma cut Parameters f_cut: float the up...
f_bar = np.median(fluxes, axis=0) sigma_f = np.var(fluxes, axis=0) bad = np.logical_and(f_bar==0, sigma_f==0) cont1 = np.abs(f_bar-1) <= f_cut cont2 = sigma_f <= sig_cut contmask = np.logical_and(cont1, cont2) contmask[bad] = False return contmask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_contpix(wl, fluxes, ivars, target_frac): """ Find continuum pix in spec, meeting a set target fraction Parameters wl: numpy ndarray rest-frame waveleng...
print("Target frac: %s" %(target_frac)) bad1 = np.median(ivars, axis=0) == SMALL bad2 = np.var(ivars, axis=0) == 0 bad = np.logical_and(bad1, bad2) npixels = len(wl)-sum(bad) f_cut = 0.0001 stepsize = 0.0001 sig_cut = 0.0001 contmask = _find_contpix_given_cuts(f_cut, sig_cut, wl, fl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_contpix_regions(wl, fluxes, ivars, frac, ranges): """ Find continuum pix in a spectrum split into chunks Parameters wl: numpy ndarray rest-frame wavele...
contmask = np.zeros(len(wl), dtype=bool) for chunk in ranges: start = chunk[0] stop = chunk[1] contmask[start:stop] = _find_contpix( wl[start:stop], fluxes[:,start:stop], ivars[:,start:stop], frac) return contmask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_data(): """ Load the reference data, and assign each object a random integer from 0 to 7. Save the IDs. """
tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0'] groups = np.random.randint(0, 8, size=len(tr_obj)) np.savez("ref_groups.npz", groups)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train(ds, ii): """ Run the training step, given a dataset object. """
print("Loading model") m = model.CannonModel(2) print("Training...") m.fit(ds) np.savez("./ex%s_coeffs.npz" %ii, m.coeffs) np.savez("./ex%s_scatters.npz" %ii, m.scatters) np.savez("./ex%s_chisqs.npz" %ii, m.chisqs) np.savez("./ex%s_pivots.npz" %ii, m.pivots) fig = m.diagnostics_lead...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weighted_std(values, weights): """ Calculate standard deviation weighted by errors """
average = np.average(values, weights=weights) variance = np.average((values-average)**2, weights=weights) return np.sqrt(variance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimate_noise(fluxes, contmask): """ Estimate the scatter in a region of the spectrum taken to be continuum """
nstars = fluxes.shape[0] scatter = np.zeros(nstars) for i,spec in enumerate(fluxes): cont = spec[contmask] scatter[i] = stats.funcs.mad_std(cont) return scatter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_ref_spectra(): """ Pull out wl, flux, ivar from files of training spectra """
data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) # Read the first file to get the wavelength array f = ff[0] data = Table.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cann...
ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # should be the same across all obj np.savez("%s/skylines.npz" %out_dir, skylines) contmask = np.load("%s/contmask_regions.npz" %data_dir)['arr_0'] scatter = estimate_noi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_full_ivar(): """ take the scatters and skylines and make final ivars """
# skylines come as an ivar # don't use them for now, because I don't really trust them... # skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0'] ref_flux = np.load("%s/ref_flux_all.npz" %DATA_DIR)['arr_0'] ref_scat = np.load("%s/ref_spec_scat_all.npz" %DATA_DIR)['arr_0'] test_flux = np.lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sinusoid(x, p, L, y): """ Return the sinusoid cont func evaluated at input x for the continuum. Parameters x: float or np.array data, input to function p: n...
N = int(len(p)/2) n = np.linspace(0, N, N+1) k = n*np.pi/L func = 0 for n in range(0, N): func += p[2*n]*np.sin(k[n]*x)+p[2*n+1]*np.cos(k[n]*x) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _weighted_median(values, weights, quantile): """ Calculate a weighted median for values above a particular quantile cut Used in pseudo continuum normalizatio...
sindx = np.argsort(values) cvalues = 1. * np.cumsum(weights[sindx]) if cvalues[-1] == 0: # means all the values are 0 return values[0] cvalues = cvalues / cvalues[-1] # div by largest value foo = sindx[cvalues > quantile] if len(foo) == 0: return values[0] indx = foo[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_cont_gaussian_smooth(wl, fluxes, ivars, w): """ Returns the weighted mean block of spectra Parameters wl: numpy ndarray wavelength vector flux: numpy n...
print("Finding the continuum") bot = np.dot(ivars, w.T) top = np.dot(fluxes*ivars, w.T) bad = bot == 0 cont = np.zeros(top.shape) cont[~bad] = top[~bad] / bot[~bad] return cont
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cont_norm_gaussian_smooth(dataset, L): """ Continuum normalize by dividing by a Gaussian-weighted smoothed spectrum Parameters dataset: Dataset the dataset ...
print("Gaussian smoothing the entire dataset...") w = gaussian_weight_matrix(dataset.wl, L) print("Gaussian smoothing the training set") cont = _find_cont_gaussian_smooth( dataset.wl, dataset.tr_flux, dataset.tr_ivar, w) norm_tr_flux, norm_tr_ivar = _cont_norm( dataset.tr_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_cont_fitfunc(fluxes, ivars, contmask, deg, ffunc, n_proc=1): """ Fit a continuum to a continuum pixels in a segment of spectra Functional form can be e...
nstars = fluxes.shape[0] npixels = fluxes.shape[1] cont = np.zeros(fluxes.shape) if n_proc == 1: for jj in range(nstars): flux = fluxes[jj,:] ivar = ivars[jj,:] pix = np.arange(0, npixels) y = flux[contmask] x = pix[contmask] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc, n_proc=1): """ Run fit_cont, dealing with spectrum in regions or chunks This is usefu...
nstars = fluxes.shape[0] npixels = fluxes.shape[1] cont = np.zeros(fluxes.shape) for chunk in ranges: start = chunk[0] stop = chunk[1] if ffunc=="chebyshev": output = _find_cont_fitfunc(fluxes[:,start:stop], ivars[:,start:stop]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_cont_running_quantile(wl, fluxes, ivars, q, delta_lambda, verbose=False): """ Perform continuum normalization using a running quantile Parameters wl: n...
cont = np.zeros(fluxes.shape) nstars = fluxes.shape[0] for jj in range(nstars): if verbose: print("cont_norm_q(): working on star [%s/%s]..." % (jj+1, nstars)) flux = fluxes[jj,:] ivar = ivars[jj,:] for ll, lam in enumerate(wl): indx = (np.where(abs(w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): """ Perform continuum normalization using running quantile, fo...
print("contnorm.py: continuum norm using running quantile") print("Taking spectra in %s chunks" % len(ranges)) nstars = fluxes.shape[0] norm_fluxes = np.zeros(fluxes.shape) norm_ivars = np.zeros(ivars.shape) for chunk in ranges: start = chunk[0] stop = chunk[1] output = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda, ranges, n_proc=2, verbose=False): """ Perform continuum normalization using runnin...
print("contnorm.py: continuum norm using running quantile") print("Taking spectra in %s chunks" % len(ranges)) # nstars = fluxes.shape[0] nchunks = len(ranges) norm_fluxes = np.zeros(fluxes.shape) norm_ivars = np.zeros(ivars.shape) for i in xrange(nchunks): chunk = ranges[i, :] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cont_norm(fluxes, ivars, cont): """ Continuum-normalize a continuous segment of spectra. Parameters fluxes: numpy ndarray pixel intensities ivars: numpy nda...
nstars = fluxes.shape[0] npixels = fluxes.shape[1] norm_fluxes = np.ones(fluxes.shape) norm_ivars = np.zeros(ivars.shape) bad = cont == 0. norm_fluxes = np.ones(fluxes.shape) norm_fluxes[~bad] = fluxes[~bad] / cont[~bad] norm_ivars = cont**2 * ivars return norm_fluxes, norm_ivars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cont_norm_regions(fluxes, ivars, cont, ranges): """ Perform continuum normalization for spectra in chunks Useful for spectra that have gaps Parameters -----...
nstars = fluxes.shape[0] norm_fluxes = np.zeros(fluxes.shape) norm_ivars = np.zeros(ivars.shape) for chunk in ranges: start = chunk[0] stop = chunk[1] output = _cont_norm(fluxes[:,start:stop], ivars[:,start:stop], cont[:,star...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters """
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', linewidth=0.3, label=r'$\theta_0$' + "= the leading fit coefficient") ax.scatter(contpix_x, contpi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 baseline_spec = coeffs_all[:,0] contmask = data.contmask contpix_x = wl[contmask] contpix_y = baseline_spec[contmask] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"): """ Produce a set of diagnostic plots for the model Parameters (optional) chisq_dist_plot_...
label_names = ds.get_plotting_labels() lams = ds.wl pivots = self.pivots npixels = len(lams) nlabels = len(pivots) chisqs = self.chisqs coeffs = self.coeffs scatters = self.scatters # Histogram of the chi squareds of ind. stars plt.hist(n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_mass(nu_max, delta_nu, teff): """ asteroseismic scaling relations """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_mass_2(mh,cm,nm,teff,logg): """ Table A2 in Martig 2016 """
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**2 - 67.6093*CplusN + 7.0486*CplusN*mh + 133.5775*CplusN*cm + 38.9439*CplusN*nm - 88...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_dist(lamost_point, training_points, coeffs): """ avg dist from one lamost point to nearest 10 training points """
diff2 = (training_points - lamost_point)**2 dist = np.sqrt(np.sum(diff2*coeffs, axis=1)) return np.mean(dist[dist.argsort()][0:10])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def name_suggest(q=None, datasetKey=None, rank=None, limit=100, offset=None, **kwargs): ''' A quick and simple autocomplete service that returns up to 20 name usages by doing prefix matching against the scientific name. Results are ordered by relevance. :param q: [str] Simple search parameter. The value for th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. :param q: [str] Query term(s) for full text s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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, **kwargs): ''' Full text search across all datasets. Results are ordere...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. :return: a string Usage:: from py...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_lookup(issue = 'CONTINENT_COUNTRY_MISMATCH') pygbif.occ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 type of data to get. Default: ``all`` :param ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def name_usage(key = None, name = None, data = 'all', language = None, datasetKey = None, uuid = None, sourceId = None, rank = None, shortname = None, limit = 100, offset = None, **kwargs): ''' Lookup details for specific names in all taxonomies in GBIF. :param key: [fixnum] A GBIF key for a taxon :param name: [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_environ(variable, value): """check if a variable is present in the environmental variables"""
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 variables"""])) else: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
user = _check_environ('GBIF_USER', user) pwd = _check_environ('GBIF_PWD', pwd) email = _check_environ('GBIF_EMAIL', email) if isinstance(queries, str): queries = [queries] keyval = [_parse_args(z) for z in queries] # USE GBIFDownload class to set up the predicates req = GbifDown...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_list(user=None, pwd=None, limit=20, offset=0): """ Lists the downloads created by a user. :param user: [str] A user name, look at env var ``GBIF_USE...
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 = gbif_GET(url, args, auth=(user, pwd)) return {'meta': {'offset': res['offset'], '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_get(key, path=".", **kwargs): """ Get a download from GBIF. :param key: [str] A key generated from a request, like that from ``download`` :param pat...
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']) url = 'http://api.gbif.org/v1/occurrence/download/request/' + key path = "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_pred_type(self, value): """set main predicate combination type :param value: (character) One of ``equals`` (``=``), ``and`` (``&``), ``or`` (``|``), ``l...
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: raise Exception("main predicate combiner not a valid operator")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_predicate(self, key, value, predicate_type='equals'): """ add key, value, type combination of a predicate :param key: query KEY parameter :param value: t...
if predicate_type not in operators: predicate_type = operator_lkup.get(predicate_type) if predicate_type: self.predicates.append({'type': predicate_type, 'key': key, 'value': value ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) as ff: reading = csv.reader(ff) for j in reading: values.append(j[0]) elif isinstance(values_list, list): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
values = self._extract_values(values_list) predicate = {'type': 'equals', 'key': key, 'value': None} predicates = [] while values: predicate['value'] = values.pop() predicates.append(predicate.copy()) self.predicates.append({'type': 'or', 'predicates': p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def name_backbone(name, rank=None, kingdom=None, phylum=None, clazz=None, order=None, family=None, genus=None, strict=False, verbose=False, offset=None, limit=100, **kwargs): ''' Lookup names in the GBIF backbone taxonomy. :param name: [str] Full scientific name potentially with authorship (required) :para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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=False, verbose=False, **kwargs): ''' Lookup names in all taxonom...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 occurrences occurrences.count_year(year = '1990,2000') ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 import occurrences occurrences.count_publishingcoun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _detect_notebook() -> bool: """Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it ...
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 SpyderKernel if isinstance(kernel.kernel, SpyderKernel): return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_layout(x: go.Layout, y: go.Layout) -> go.Layout: """Merge attributes from two layouts."""
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(yjson)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.isoformat() for y in x.dt.to_pydatetime()] except AttributeError: pass return x