_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q275700
D.filter_threshold
test
def filter_threshold(self, analyte, threshold): """ Apply threshold filter. Generates threshold filters for the given analytes above and below the specified threshold. Two filters are created with prefixes '_above' and '_below'. '_above' keeps all the data above the...
python
{ "resource": "" }
q275701
D.filter_gradient_threshold
test
def filter_gradient_threshold(self, analyte, win, threshold, recalc=True): """ Apply gradient threshold filter. Generates threshold filters for the given analytes above and below the specified threshold. Two filters are created with prefixes '_above' and '_below'. '...
python
{ "resource": "" }
q275702
D.calc_correlation
test
def calc_correlation(self, x_analyte, y_analyte, window=15, filt=True, recalc=True): """ Calculate local correlation between two analytes. Parameters ---------- x_analyte, y_analyte : str The names of the x and y analytes to correlate. window : int, None ...
python
{ "resource": "" }
q275703
D.filter_correlation
test
def filter_correlation(self, x_analyte, y_analyte, window=15, r_threshold=0.9, p_threshold=0.05, filt=True, recalc=False): """ Calculate correlation filter. Parameters ---------- x_analyte, y_analyte : str The names of the x and y analytes ...
python
{ "resource": "" }
q275704
D.filter_new
test
def filter_new(self, name, filt_str): """ Make new filter from combination of other filters. Parameters ---------- name : str The name of the new filter. Should be unique. filt_str : str A logical combination of partial strings which will create ...
python
{ "resource": "" }
q275705
D.get_params
test
def get_params(self): """ Returns paramters used to process data. Returns ------- dict dict of analysis parameters """ outputs = ['sample', 'ratio_params', 'despike_params', 'autorange_params', ...
python
{ "resource": "" }
q275706
histograms
test
def histograms(dat, keys=None, bins=25, logy=False, cmap=None, ncol=4): """ Plot histograms of all items in dat. Parameters ---------- dat : dict Data in {key: array} pairs. keys : arra-like The keys in dat that you want to plot. If None, all are plotted. bins : int ...
python
{ "resource": "" }
q275707
summary_stats
test
def summary_stats(x, y, nm=None): """ Compute summary statistics for paired x, y data. Tests ----- Parameters ---------- x, y : array-like Data to compare nm : str (optional) Index value of created dataframe. Returns ------- pandas dataframe of statistics. ...
python
{ "resource": "" }
q275708
load_reference_data
test
def load_reference_data(name=None): """ Fetch LAtools reference data from online repository. Parameters ---------- name : str< Which data to download. Can be one of 'culture_reference', 'culture_test', 'downcore_reference', 'downcore_test', 'iolite_reference' or 'zircon_refe...
python
{ "resource": "" }
q275709
AllInstances.lookup
test
def lookup(self, TC: type, G: type) -> Optional[TypeClass]: ''' Find an instance of the type class `TC` for type `G`. Iterates `G`'s parent classes, looking up instances for each, checking whether the instance is a subclass of the target type class `TC`. ''' if isinstance...
python
{ "resource": "" }
q275710
elements
test
def elements(all_isotopes=True): """ Loads a DataFrame of all elements and isotopes. Scraped from https://www.webelements.com/ Returns ------- pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent) """ el = pd.read_pickle(pkgrs.resource_filename('latool...
python
{ "resource": "" }
q275711
calc_M
test
def calc_M(molecule): """ Returns molecular weight of molecule. Where molecule is in standard chemical notation, e.g. 'CO2', 'HCO3' or B(OH)4 Returns ------- molecular_weight : float """ # load periodic table els = elements() # define regexs parens = re.compile('\(([A...
python
{ "resource": "" }
q275712
gen_keywords
test
def gen_keywords(*args: Union[ANSIColors, ANSIStyles], **kwargs: Union[ANSIColors, ANSIStyles]) -> tuple: '''generate single escape sequence mapping.''' fields: tuple = tuple() values: tuple = tuple() for tpl in args: fields += tpl._fields values += tpl for prefix, tpl in kwargs.item...
python
{ "resource": "" }
q275713
annihilate
test
def annihilate(predicate: tuple, stack: tuple) -> tuple: '''Squash and reduce the input stack. Removes the elements of input that match predicate and only keeps the last match at the end of the stack. ''' extra = tuple(filter(lambda x: x not in predicate, stack)) head = reduce(lambda x, y: y if ...
python
{ "resource": "" }
q275714
dedup
test
def dedup(stack: tuple) -> tuple: '''Remove duplicates from the stack in first-seen order.''' # Initializes with an accumulator and then reduces the stack with first match # deduplication. reducer = lambda x, y: x if y in x else x + (y,) return reduce(reducer, stack, tuple())
python
{ "resource": "" }
q275715
gauss_weighted_stats
test
def gauss_weighted_stats(x, yarray, x_new, fwhm): """ Calculate gaussian weigted moving mean, SD and SE. Parameters ---------- x : array-like The independent variable yarray : (n,m) array Where n = x.size, and m is the number of dependent variables to smooth. x_new :...
python
{ "resource": "" }
q275716
gauss
test
def gauss(x, *p): """ Gaussian function. Parameters ---------- x : array_like Independent variable. *p : parameters unpacked to A, mu, sigma A = amplitude, mu = centre, sigma = width Return ------ array_like gaussian descriped by *p. """ A, mu, sigma = p...
python
{ "resource": "" }
q275717
stderr
test
def stderr(a): """ Calculate the standard error of a. """ return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))
python
{ "resource": "" }
q275718
analyse._get_samples
test
def _get_samples(self, subset=None): """ Helper function to get sample names from subset. Parameters ---------- subset : str Subset name. If None, returns all samples. Returns ------- List of sample names """ if subset is None...
python
{ "resource": "" }
q275719
analyse.despike
test
def despike(self, expdecay_despiker=False, exponent=None, noise_despiker=True, win=3, nlim=12., exponentplot=False, maxiter=4, autorange_kwargs={}, focus_stage='rawdata'): """ Despikes data with exponential decay and noise filters. Parameters ---------- ...
python
{ "resource": "" }
q275720
analyse.bkg_calc_weightedmean
test
def bkg_calc_weightedmean(self, analytes=None, weight_fwhm=None, n_min=20, n_max=None, cstep=None, bkg_filter=False, f_win=7, f_n_lim=3, focus_stage='despiked'): """ Background calculation using a gaussian weighted mean. Parameters ...
python
{ "resource": "" }
q275721
analyse.bkg_calc_interp1d
test
def bkg_calc_interp1d(self, analytes=None, kind=1, n_min=10, n_max=None, cstep=None, bkg_filter=False, f_win=7, f_n_lim=3, focus_stage='despiked'): """ Background calculation using a 1D interpolation. scipy.interpolate.interp1D is used for interpolation. Param...
python
{ "resource": "" }
q275722
analyse.bkg_subtract
test
def bkg_subtract(self, analytes=None, errtype='stderr', focus_stage='despiked'): """ Subtract calculated background from data. Must run bkg_calc first! Parameters ---------- analytes : str or iterable Which analyte(s) to subtract. errtype : str ...
python
{ "resource": "" }
q275723
analyse.ratio
test
def ratio(self, internal_standard=None): """ Calculates the ratio of all analytes to a single analyte. Parameters ---------- internal_standard : str The name of the analyte to divide all other analytes by. Returns ------- None ...
python
{ "resource": "" }
q275724
analyse.make_subset
test
def make_subset(self, samples=None, name=None): """ Creates a subset of samples, which can be treated independently. Parameters ---------- samples : str or array - like Name of sample, or list of sample names. name : (optional) str or number The n...
python
{ "resource": "" }
q275725
analyse.filter_gradient_threshold_percentile
test
def filter_gradient_threshold_percentile(self, analyte, percentiles, level='population', win=15, filt=False, samples=None, subset=None): """ Calculate a gradient threshold filter to the data. Generates two filters above and below the threshold value ...
python
{ "resource": "" }
q275726
analyse.fit_classifier
test
def fit_classifier(self, name, analytes, method, samples=None, subset=None, filt=True, sort_by=0, **kwargs): """ Create a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier. ...
python
{ "resource": "" }
q275727
analyse.apply_classifier
test
def apply_classifier(self, name, samples=None, subset=None): """ Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the...
python
{ "resource": "" }
q275728
analyse.filter_correlation
test
def filter_correlation(self, x_analyte, y_analyte, window=None, r_threshold=0.9, p_threshold=0.05, filt=True, samples=None, subset=None): """ Applies a correlation filter to the data. Calculates a rolling correlation between every `window` p...
python
{ "resource": "" }
q275729
analyse.filter_on
test
def filter_on(self, filt=None, analyte=None, samples=None, subset=None, show_status=False): """ Turns data filters on for particular analytes and samples. Parameters ---------- filt : optional, str or array_like Name, partial name or list of names of filters. Support...
python
{ "resource": "" }
q275730
analyse.filter_off
test
def filter_off(self, filt=None, analyte=None, samples=None, subset=None, show_status=False): """ Turns data filters off for particular analytes and samples. Parameters ---------- filt : optional, str or array_like Name, partial name or list of names of filters. Suppo...
python
{ "resource": "" }
q275731
analyse.filter_status
test
def filter_status(self, sample=None, subset=None, stds=False): """ Prints the current status of filters for specified samples. Parameters ---------- sample : str Which sample to print. subset : str Specify a subset stds : bool ...
python
{ "resource": "" }
q275732
analyse.filter_defragment
test
def filter_defragment(self, threshold, mode='include', filt=True, samples=None, subset=None): """ Remove 'fragments' from the calculated filter Parameters ---------- threshold : int Contiguous data regions that contain this number or fewer points are cons...
python
{ "resource": "" }
q275733
analyse.filter_nremoved
test
def filter_nremoved(self, filt=True, quiet=False): """ Report how many data are removed by the active filters. """ rminfo = {} for n in self.subsets['All_Samples']: s = self.data[n] rminfo[n] = s.filt_nremoved(filt) if not quiet: maxL =...
python
{ "resource": "" }
q275734
analyse.gradient_histogram
test
def gradient_histogram(self, analytes=None, win=15, filt=False, bins=None, samples=None, subset=None, recalc=True, ncol=4): """ Plot a histogram of the gradients in all samples. Parameters ---------- filt : str, dict or bool Either logical filter expression contained...
python
{ "resource": "" }
q275735
analyse.gradient_crossplot
test
def gradient_crossplot(self, analytes=None, win=15, lognorm=True, bins=25, filt=False, samples=None, subset=None, figsize=(12, 12), save=False, colourful=True, mode='hist2d', recalc=True, **kwargs): """ Plot analyte gradien...
python
{ "resource": "" }
q275736
analyse.histograms
test
def histograms(self, analytes=None, bins=25, logy=False, filt=False, colourful=True): """ Plot histograms of analytes. Parameters ---------- analytes : optional, array_like or str The analyte(s) to plot. Defaults to all analytes. bins : int...
python
{ "resource": "" }
q275737
analyse.trace_plots
test
def trace_plots(self, analytes=None, samples=None, ranges=False, focus=None, outdir=None, filt=None, scale='log', figsize=[10, 4], stats=False, stat='nanmean', err='nanstd', subset='All_Analyses'): """ Plot analytes as a function of time. ...
python
{ "resource": "" }
q275738
analyse.gradient_plots
test
def gradient_plots(self, analytes=None, win=15, samples=None, ranges=False, focus=None, outdir=None, figsize=[10, 4], subset='All_Analyses'): """ Plot analyte gradients as a function of time. Parameters ---------- analytes : optional...
python
{ "resource": "" }
q275739
analyse.filter_reports
test
def filter_reports(self, analytes, filt_str='all', nbin=5, samples=None, outdir=None, subset='All_Samples'): """ Plot filter reports for all filters that contain ``filt_str`` in the name. """ if outdir is None: outdir = self.report_dir + '/filte...
python
{ "resource": "" }
q275740
analyse.sample_stats
test
def sample_stats(self, analytes=None, filt=True, stats=['mean', 'std'], eachtrace=True, csf_dict={}): """ Calculate sample statistics. Returns samples, analytes, and arrays of statistics of shape (samples, analytes). Statistics are calculated ...
python
{ "resource": "" }
q275741
analyse.getstats
test
def getstats(self, save=True, filename=None, samples=None, subset=None, ablation_time=False): """ Return pandas dataframe of all sample statistics. """ slst = [] if samples is not None: subset = self.make_subset(samples) samples = self._get_samples(subset) ...
python
{ "resource": "" }
q275742
analyse._minimal_export_traces
test
def _minimal_export_traces(self, outdir=None, analytes=None, samples=None, subset='All_Analyses'): """ Used for exporting minimal dataset. DON'T USE. """ if analytes is None: analytes = self.analytes elif isinstance(analytes, str): ...
python
{ "resource": "" }
q275743
analyse.export_traces
test
def export_traces(self, outdir=None, focus_stage=None, analytes=None, samples=None, subset='All_Analyses', filt=False, zip_archive=False): """ Function to export raw data. Parameters ---------- outdir : str directory to save toe traces. Defaults...
python
{ "resource": "" }
q275744
analyse.save_log
test
def save_log(self, directory=None, logname=None, header=None): """ Save analysis.lalog in specified location """ if directory is None: directory = self.export_dir if not os.path.isdir(directory): directory = os.path.dirname(directory) if logname i...
python
{ "resource": "" }
q275745
analyse.minimal_export
test
def minimal_export(self, target_analytes=None, path=None): """ Exports a analysis parameters, standard info and a minimal dataset, which can be imported by another user. Parameters ---------- target_analytes : str or iterable Which analytes to include in the ...
python
{ "resource": "" }
q275746
by_regex
test
def by_regex(file, outdir=None, split_pattern=None, global_header_rows=0, fname_pattern=None, trim_tail_lines=0, trim_head_lines=0): """ Split one long analysis file into multiple smaller ones. Parameters ---------- file : str The path to the file you want to split. outdir : str ...
python
{ "resource": "" }
q275747
Foldable.fold_map
test
def fold_map(self, fa: F[A], z: B, f: Callable[[A], B], g: Callable[[Z, B], Z]=operator.add) -> Z: ''' map `f` over the traversable, then fold over the result using the supplied initial element `z` and operation `g`, defaulting to addition for the latter. ''' mapped = Functor.fat...
python
{ "resource": "" }
q275748
pca_plot
test
def pca_plot(pca, dt, xlabs=None, mode='scatter', lognorm=True): """ Plot a fitted PCA, and all components. """ nc = pca.n_components f = np.arange(pca.n_features_) cs = list(itertools.combinations(range(nc), 2)) ind = ~np.apply_along_axis(any, 1, np.isnan(dt)) cylim = (pca.co...
python
{ "resource": "" }
q275749
bayes_scale
test
def bayes_scale(s): """ Remove mean and divide by standard deviation, using bayes_kvm statistics. """ if sum(~np.isnan(s)) > 1: bm, bv, bs = bayes_mvs(s[~np.isnan(s)]) return (s - bm.statistic) / bs.statistic else: return np.full(s.shape, np.nan)
python
{ "resource": "" }
q275750
median_scaler
test
def median_scaler(s): """ Remove median, divide by IQR. """ if sum(~np.isnan(s)) > 2: ss = s[~np.isnan(s)] median = np.median(ss) IQR = np.diff(np.percentile(ss, [25, 75])) return (s - median) / IQR else: return np.full(s.shape, np.nan)
python
{ "resource": "" }
q275751
noise_despike
test
def noise_despike(sig, win=3, nlim=24., maxiter=4): """ Apply standard deviation filter to remove anomalous values. Parameters ---------- win : int The window used to calculate rolling statistics. nlim : float The number of standard deviations above the rolling mean abov...
python
{ "resource": "" }
q275752
expdecay_despike
test
def expdecay_despike(sig, expdecay_coef, tstep, maxiter=3): """ Apply exponential decay filter to remove physically impossible data based on instrumental washout. The filter is re-applied until no more points are removed, or maxiter is reached. Parameters ---------- exponent : float Ex...
python
{ "resource": "" }
q275753
filt.add
test
def add(self, name, filt, info='', params=(), setn=None): """ Add filter. Parameters ---------- name : str filter name filt : array_like boolean filter array info : str informative description of the filter params : tup...
python
{ "resource": "" }
q275754
filt.remove
test
def remove(self, name=None, setn=None): """ Remove filter. Parameters ---------- name : str name of the filter to remove setn : int or True int: number of set to remove True: remove all filters in set that 'name' belongs to Re...
python
{ "resource": "" }
q275755
filt.clear
test
def clear(self): """ Clear all filters. """ self.components = {} self.info = {} self.params = {} self.switches = {} self.keys = {} self.index = {} self.sets = {} self.maxset = -1 self.n = 0 for a in self.analytes: ...
python
{ "resource": "" }
q275756
filt.clean
test
def clean(self): """ Remove unused filters. """ for f in sorted(self.components.keys()): unused = not any(self.switches[a][f] for a in self.analytes) if unused: self.remove(f)
python
{ "resource": "" }
q275757
filt.fuzzmatch
test
def fuzzmatch(self, fuzzkey, multi=False): """ Identify a filter by fuzzy string matching. Partial ('fuzzy') matching performed by `fuzzywuzzy.fuzzy.ratio` Parameters ---------- fuzzkey : str A string that partially matches one filter name more than the othe...
python
{ "resource": "" }
q275758
filt.make_fromkey
test
def make_fromkey(self, key): """ Make filter from logical expression. Takes a logical expression as an input, and returns a filter. Used for advanced filtering, where combinations of nested and/or filters are desired. Filter names must exactly match the names listed by print(fil...
python
{ "resource": "" }
q275759
filt.grab_filt
test
def grab_filt(self, filt, analyte=None): """ Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str name of...
python
{ "resource": "" }
q275760
filt.get_info
test
def get_info(self): """ Get info for all filters. """ out = '' for k in sorted(self.components.keys()): out += '{:s}: {:s}'.format(k, self.info[k]) + '\n' return(out)
python
{ "resource": "" }
q275761
_log
test
def _log(func): """ Function for logging method calls and parameters """ @wraps(func) def wrapper(self, *args, **kwargs): a = func(self, *args, **kwargs) self.log.append(func.__name__ + ' :: args={} kwargs={}'.format(args, kwargs)) return a return wrapper
python
{ "resource": "" }
q275762
write_logfile
test
def write_logfile(log, header, file_name): """ Write and analysis log to a file. Parameters ---------- log : list latools.analyse analysis log header : list File header lines. file_name : str Destination file. If no file extension specified, uses '.lalog' ...
python
{ "resource": "" }
q275763
read_logfile
test
def read_logfile(log_file): """ Reads an latools analysis.log file, and returns dicts of arguments. Parameters ---------- log_file : str Path to an analysis.log file produced by latools. Returns ------- runargs, paths : tuple Two dictionaries. runargs contains all t...
python
{ "resource": "" }
q275764
autologin
test
def autologin(function, timeout=TIMEOUT): """Decorator that will try to login and redo an action before failing.""" @wraps(function) async def wrapper(self, *args, **kwargs): """Wrap a function with timeout.""" try: async with async_timeout.timeout(timeout): retur...
python
{ "resource": "" }
q275765
get_information
test
async def get_information(): """Example of printing the inbox.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) result = await modem.informa...
python
{ "resource": "" }
q275766
send_message
test
async def send_message(): """Example of sending a message.""" jar = aiohttp.CookieJar(unsafe=True) websession = aiohttp.ClientSession(cookie_jar=jar) modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession) await modem.login(password=sys.argv[2]) await modem.sms(phone=sys.argv[3...
python
{ "resource": "" }
q275767
parse
test
def parse(file_or_string): """Parse a file-like object or string. Args: file_or_string (file, str): File-like object or string. Returns: ParseResults: instance of pyparsing parse results. """ from mysqlparse.grammar.sql_file import sql_file_syntax if hasattr(file_or_string, 'r...
python
{ "resource": "" }
q275768
nbviewer_link
test
def nbviewer_link(url): """Return the link to the Jupyter nbviewer for the given notebook url""" if six.PY2: from urlparse import urlparse as urlsplit else: from urllib.parse import urlsplit info = urlsplit(url) domain = info.netloc url_type = 'github' if domain == 'github.com' e...
python
{ "resource": "" }
q275769
NotebookProcessor.thumbnail_div
test
def thumbnail_div(self): """The string for creating the thumbnail of this example""" return self.THUMBNAIL_TEMPLATE.format( snippet=self.get_description()[1], thumbnail=self.thumb_file, ref_name=self.reference)
python
{ "resource": "" }
q275770
NotebookProcessor.code_div
test
def code_div(self): """The string for creating a code example for the gallery""" code_example = self.code_example if code_example is None: return None return self.CODE_TEMPLATE.format( snippet=self.get_description()[1], code=code_example, ref_name=self...
python
{ "resource": "" }
q275771
NotebookProcessor.code_example
test
def code_example(self): """The code example out of the notebook metadata""" if self._code_example is not None: return self._code_example return getattr(self.nb.metadata, 'code_example', None)
python
{ "resource": "" }
q275772
NotebookProcessor.url
test
def url(self): """The url on jupyter nbviewer for this notebook or None if unknown""" if self._url is not None: url = self._url else: url = getattr(self.nb.metadata, 'url', None) if url is not None: return nbviewer_link(url)
python
{ "resource": "" }
q275773
NotebookProcessor.get_out_file
test
def get_out_file(self, ending='rst'): """get the output file with the specified `ending`""" return os.path.splitext(self.outfile)[0] + os.path.extsep + ending
python
{ "resource": "" }
q275774
NotebookProcessor.process_notebook
test
def process_notebook(self, disable_warnings=True): """Process the notebook and create all the pictures and files This method runs the notebook using the :mod:`nbconvert` and :mod:`nbformat` modules. It creates the :attr:`outfile` notebook, a python and a rst file""" infile = sel...
python
{ "resource": "" }
q275775
NotebookProcessor.create_py
test
def create_py(self, nb, force=False): """Create the python script from the notebook node""" # Although we would love to simply use ``nbconvert.export_python(nb)`` # this causes troubles in other cells processed by the ipython # directive. Instead of getting something like ``Out [5]:``, w...
python
{ "resource": "" }
q275776
NotebookProcessor.data_download
test
def data_download(self, files): """Create the rst string to download supplementary data""" if len(files) > 1: return self.DATA_DOWNLOAD % ( ('\n\n' + ' '*8) + ('\n' + ' '*8).join( '* :download:`%s`' % f for f in files)) return self.DATA_DOWNLOAD % ...
python
{ "resource": "" }
q275777
NotebookProcessor.create_thumb
test
def create_thumb(self): """Create the thumbnail for html output""" thumbnail_figure = self.copy_thumbnail_figure() if thumbnail_figure is not None: if isinstance(thumbnail_figure, six.string_types): pic = thumbnail_figure else: pic = self.p...
python
{ "resource": "" }
q275778
NotebookProcessor.get_description
test
def get_description(self): """Get summary and description of this notebook""" def split_header(s, get_header=True): s = s.lstrip().rstrip() parts = s.splitlines() if parts[0].startswith('#'): if get_header: header = re.sub('#+\s*', ...
python
{ "resource": "" }
q275779
NotebookProcessor.scale_image
test
def scale_image(self, in_fname, out_fname, max_width, max_height): """Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down """ # local import to avoid testing depende...
python
{ "resource": "" }
q275780
NotebookProcessor.save_thumbnail
test
def save_thumbnail(self, image_path): """Save the thumbnail image""" thumb_dir = os.path.join(os.path.dirname(image_path), 'thumb') create_dirs(thumb_dir) thumb_file = os.path.join(thumb_dir, '%s_thumb.png' % self.reference) if os.path.exists(im...
python
{ "resource": "" }
q275781
NotebookProcessor.copy_thumbnail_figure
test
def copy_thumbnail_figure(self): """The integer of the thumbnail figure""" ret = None if self._thumbnail_figure is not None: if not isstring(self._thumbnail_figure): ret = self._thumbnail_figure else: ret = osp.join(osp.dirname(self.outfile...
python
{ "resource": "" }
q275782
Gallery.get_url
test
def get_url(self, nbfile): """Return the url corresponding to the given notebook file Parameters ---------- nbfile: str The path of the notebook relative to the corresponding :attr:``in_dir`` Returns ------- str or None The ur...
python
{ "resource": "" }
q275783
Command.get_db_change_languages
test
def get_db_change_languages(self, field_name, db_table_fields): """ get only db changes fields """ for lang_code, lang_name in get_languages(): if get_real_fieldname(field_name, lang_code) not in db_table_fields: yield lang_code for db_table_field in db_table_fields: ...
python
{ "resource": "" }
q275784
default_value
test
def default_value(field): ''' When accessing to the name of the field itself, the value in the current language will be returned. Unless it's set, the value in the default language will be returned. ''' def default_value_func(self): attname = lambda x: get_real_fieldname(field, x) ...
python
{ "resource": "" }
q275785
process
test
def process(thumbnail_file, size, **kwargs): """ Post processors are functions that receive file objects, performs necessary operations and return the results as file objects. """ from . import conf size_dict = conf.SIZES[size] for processor in size_dict['POST_PROCESSORS']: processo...
python
{ "resource": "" }
q275786
ImageField.pre_save
test
def pre_save(self, model_instance, add): """ Process the source image through the defined processors. """ file = getattr(model_instance, self.attname) if file and not file._committed: image_file = file if self.resize_source_to: file.seek(0...
python
{ "resource": "" }
q275787
ThumbnailManager._refresh_cache
test
def _refresh_cache(self): """Populate self._thumbnails.""" self._thumbnails = {} metadatas = self.metadata_backend.get_thumbnails(self.source_image.name) for metadata in metadatas: self._thumbnails[metadata.size] = Thumbnail(metadata=metadata, storage=self.storage)
python
{ "resource": "" }
q275788
ThumbnailManager.all
test
def all(self): """ Return all thumbnails in a dict format. """ if self._thumbnails is not None: return self._thumbnails self._refresh_cache() return self._thumbnails
python
{ "resource": "" }
q275789
ThumbnailManager.create
test
def create(self, size): """ Creates and return a thumbnail of a given size. """ thumbnail = images.create(self.source_image.name, size, self.metadata_backend, self.storage) return thumbnail
python
{ "resource": "" }
q275790
ThumbnailManager.delete
test
def delete(self, size): """ Deletes a thumbnail of a given size """ images.delete(self.source_image.name, size, self.metadata_backend, self.storage) del(self._thumbnails[size])
python
{ "resource": "" }
q275791
create
test
def create(source_name, size, metadata_backend=None, storage_backend=None): """ Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadat...
python
{ "resource": "" }
q275792
get
test
def get(source_name, size, metadata_backend=None, storage_backend=None): """ Returns a Thumbnail instance, or None if thumbnail does not yet exist. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backend...
python
{ "resource": "" }
q275793
delete
test
def delete(source_name, size, metadata_backend=None, storage_backend=None): """ Deletes a thumbnail file and its relevant metadata. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadata_backend = backends.metadata.get_b...
python
{ "resource": "" }
q275794
LoopbackProvider.received
test
def received(self, src, body): """ Simulate an incoming message :type src: str :param src: Message source :type boby: str | unicode :param body: Message body :rtype: IncomingMessage """ # Create the message self._msgid += 1 ...
python
{ "resource": "" }
q275795
LoopbackProvider.subscribe
test
def subscribe(self, number, callback): """ Register a virtual subscriber which receives messages to the matching number. :type number: str :param number: Subscriber phone number :type callback: callable :param callback: A callback(OutgoingMessage) which handles t...
python
{ "resource": "" }
q275796
MessageStatus.states
test
def states(self): """ Get the set of states. Mostly used for pretty printing :rtype: set :returns: Set of 'accepted', 'delivered', 'expired', 'error' """ ret = set() if self.accepted: ret.add('accepted') if self.delivered: ret.add(...
python
{ "resource": "" }
q275797
Gateway.add_provider
test
def add_provider(self, name, Provider, **config): """ Register a provider on the gateway The first provider defined becomes the default one: used in case the routing function has no better idea. :type name: str :param name: Provider name that will be used to uniquely identi...
python
{ "resource": "" }
q275798
Gateway.send
test
def send(self, message): """ Send a message object :type message: data.OutgoingMessage :param message: The message to send :rtype: data.OutgoingMessage :returns: The sent message with populated fields :raises AssertionError: wrong provider name encoun...
python
{ "resource": "" }
q275799
Gateway.receiver_blueprint_for
test
def receiver_blueprint_for(self, name): """ Get a Flask blueprint for the named provider that handles incoming messages & status reports Note: this requires Flask microframework. :rtype: flask.blueprints.Blueprint :returns: Flask Blueprint, fully functional :rai...
python
{ "resource": "" }