_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21900 | Curve.plot | train | def plot(self, ax=None, legend=None, return_fig=False, **kwargs):
"""
Plot a curve.
Args:
ax (ax): A matplotlib axis.
legend (striplog.legend): A legend. Optional.
return_fig (bool): whether to return the matplotlib figure.
Default False.
kwargs: Arguments for ``ax.set()``
Returns:
ax. If you passed in an ax, otherwise None.
"""
if ax is None:
fig = plt.figure(figsize=(2, 10))
ax = fig.add_subplot(111)
return_ax = False
else:
return_ax = True
d = None
if legend is not None:
try:
d = legend.get_decor(self)
except:
pass
if d is not None:
kwargs['color'] = d.colour
kwargs['lw'] = getattr(d, 'lineweight', None) or getattr(d, 'lw', 1)
kwargs['ls'] = getattr(d, 'linestyle', None) or getattr(d, 'ls', '-')
# Attempt to get axis parameters from decor.
axkwargs = {}
xlim = getattr(d, 'xlim', None)
if xlim is not None:
axkwargs['xlim'] = list(map(float, xlim.split(',')))
xticks = getattr(d, 'xticks', None)
| python | {
"resource": ""
} |
q21901 | Curve.interpolate | train | def interpolate(self):
"""
Interpolate across any missing zones.
TODO
Allow spline interpolation.
"""
| python | {
"resource": ""
} |
q21902 | Curve.interpolate_where | train | def interpolate_where(self, condition):
"""
Remove then interpolate across
"""
| python | {
"resource": ""
} |
q21903 | Curve.read_at | train | def read_at(self, d, **kwargs):
"""
Read the log at a specific depth or an array of depths.
Args:
d (float or array-like)
interpolation (str)
| python | {
"resource": ""
} |
q21904 | Curve.quality | train | def quality(self, tests, alias=None):
"""
Run a series of tests and return the corresponding results.
Args:
tests (list): a list of functions.
alias (dict): a dictionary mapping mnemonics to lists of mnemonics.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# Gather the test s.
# First, anything called 'all', 'All', or 'ALL'.
# Second, anything with the name of the curve we're in now.
# Third, anything that the alias list has for this curve.
# (This requires a reverse look-up so it's a bit messy.)
this_tests =\
tests.get('each', [])+tests.get('Each', [])+tests.get('EACH', [])\ | python | {
"resource": ""
} |
q21905 | Curve.block | train | def block(self,
cutoffs=None,
values=None,
n_bins=0,
right=False,
function=None):
"""
Block a log based on number of bins, or on cutoffs.
Args:
cutoffs (array)
values (array): the values to map to. Defaults to [0, 1, 2,...]
n_bins (int)
right (bool)
function (function): transform the log if you want.
Returns:
Curve.
"""
# We'll return a copy.
params = self.__dict__.copy()
if (values is not None) and (cutoffs is None):
cutoffs = values[1:]
if (cutoffs is None) and (n_bins == 0):
cutoffs = np.mean(self)
if (n_bins != 0) and (cutoffs is None):
mi, ma = np.amin(self), np.amax(self)
cutoffs = np.linspace(mi, ma, n_bins+1)
cutoffs = cutoffs[:-1]
try: # To use cutoff as a list.
data = np.digitize(self, cutoffs, right)
except ValueError: # It's just a number.
data = np.digitize(self, [cutoffs], right)
if (function is None) and (values is None):
return Curve(data, params=params)
data = data.astype(float)
# Set | python | {
"resource": ""
} |
q21906 | Curve.apply | train | def apply(self, window_length, samples=True, func1d=None):
"""
Runs any kind of function over a window.
Args:
window_length (int): the window length. Required.
samples (bool): window length is in samples. Use False for a window
length given in metres.
func1d (function): a function that takes a 1D array and returns a
scalar. Default: ``np.mean()``.
Returns:
Curve.
| python | {
"resource": ""
} |
q21907 | Header.from_csv | train | def from_csv(cls, csv_file):
"""
Not implemented. Will provide a route from CSV file.
"""
try:
param_dict = csv.DictReader(csv_file)
| python | {
"resource": ""
} |
q21908 | write_row | train | def write_row(dictionary, card, log):
"""
Processes a single row from the file.
"""
rowhdr = {'card': card, 'log': log}
# Do this as a list of 1-char strings.
# Can't use a string b/c strings are immutable.
row = [' '] * 80
# Make the row header.
| python | {
"resource": ""
} |
q21909 | Synthetic.basis | train | def basis(self):
"""
Compute basis rather than storing it.
"""
precision_adj = self.dt / 100 | python | {
"resource": ""
} |
q21910 | Synthetic.as_curve | train | def as_curve(self, start=None, stop=None):
"""
Get the synthetic as a Curve, in depth. Facilitates plotting along-
side other curve data.
"""
params = {'start': start or getattr(self, 'z start', None),
| python | {
"resource": ""
} |
q21911 | Synthetic.plot | train | def plot(self, ax=None, return_fig=False, **kwargs):
"""
Plot a synthetic.
Args:
ax (ax): A matplotlib axis.
legend (Legend): For now, only here to match API for other plot
methods.
return_fig (bool): whether to return the matplotlib figure.
Default False.
Returns:
ax. If you passed in an ax, otherwise None.
"""
if ax is None:
fig = plt.figure(figsize=(2, 10))
ax = fig.add_subplot(111)
return_ax = False
else:
| python | {
"resource": ""
} |
q21912 | no_gaps | train | def no_gaps(curve):
"""
Check for gaps, after ignoring any NaNs at | python | {
"resource": ""
} |
q21913 | no_spikes | train | def no_spikes(tolerance):
"""
Arg ``tolerance`` is the number of spiky samples allowed.
"""
def no_spikes(curve):
diff = | python | {
"resource": ""
} |
q21914 | Well.from_lasio | train | def from_lasio(cls, l, remap=None, funcs=None, data=True, req=None, alias=None, fname=None):
"""
Constructor. If you already have the lasio object, then this makes a
well object from it.
Args:
l (lasio object): a lasio object.
remap (dict): Optional. A dict of 'old': 'new' LAS field names.
funcs (dict): Optional. A dict of 'las field': function() for
implementing a transform before loading. Can be a lambda.
data (bool): Whether to load curves or not.
req (dict): An alias list, giving all required curves. If not
all of the aliases are present, the well is empty.
Returns:
well. The well object.
"""
# Build a dict of curves.
curve_params = {}
for field, (sect, code) in LAS_FIELDS['data'].items():
curve_params[field] = utils.lasio_get(l,
sect,
code,
remap=remap,
funcs=funcs)
# This is annoying, but I need the whole depth array to
# deal with edge cases, eg non-uniform sampling.
# Add all required curves together.
if req:
reqs = utils.flatten_list([v for k, v in alias.items() if k in req])
# Using lasio's idea of depth in metres:
if l.depth_m[0] < l.depth_m[1]:
curve_params['depth'] = l.depth_m
else:
curve_params['depth'] = np.flipud(l.depth_m)
# Make the curve dictionary.
depth_curves = ['DEPT', 'TIME']
if data and req:
curves = {c.mnemonic: Curve.from_lasio_curve(c, **curve_params)
for c in l.curves
if (c.mnemonic[:4] not in depth_curves)
and (c.mnemonic in reqs)}
elif data and not req:
curves = {c.mnemonic: Curve.from_lasio_curve(c, **curve_params)
for c in l.curves
if (c.mnemonic[:4] not in depth_curves)}
| python | {
"resource": ""
} |
q21915 | Well.to_lasio | train | def to_lasio(self, keys=None, basis=None):
"""
Makes a lasio object from the current well.
Args:
basis (ndarray): Optional. The basis to export the curves in. If
you don't specify one, it will survey all the curves with
``survey_basis()``.
keys (list): List of strings: the keys of the data items to
include, if not all of them. You can have nested lists, such
as you might use for ``tracks`` in ``well.plot()``.
Returns:
lasio. The lasio object.
"""
# Create an empty lasio object.
l = lasio.LASFile()
l.well.DATE = str(datetime.datetime.today())
# Deal with header.
for obj, dic in LAS_FIELDS.items():
if obj == 'data':
continue
for attr, (sect, item) in dic.items():
value = getattr(getattr(self, obj), attr, None)
try:
getattr(l, sect)[item].value = value
except:
h = lasio.HeaderItem(item, "", value, "")
getattr(l, sect)[item] = h
# Clear curves from header portion.
l.header['Curves'] = []
# Add a depth basis.
if basis is None:
basis = self.survey_basis(keys=keys)
try:
l.add_curve('DEPT', basis)
except:
raise Exception("Please provide a depth basis.")
# Add meta from basis.
setattr(l.well, 'STRT', basis[0])
setattr(l.well, 'STOP', basis[-1])
setattr(l.well, 'STEP', basis[1]-basis[0])
# Add data entities.
other = ''
if keys is None:
keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
else:
| python | {
"resource": ""
} |
q21916 | Well._plot_depth_track | train | def _plot_depth_track(self, ax, md, kind='MD'):
"""
Private function. Depth track plotting.
Args:
ax (ax): A matplotlib axis.
md (ndarray): The measured depths of the track.
kind (str): The kind of track to plot.
Returns:
ax.
"""
if kind == 'MD':
ax.set_yscale('bounded', vmin=md.min(), vmax=md.max())
# ax.set_ylim([md.max(), md.min()])
elif kind == 'TVD':
tvd = self.location.md2tvd(md)
ax.set_yscale('piecewise', x=tvd, y=md)
# ax.set_ylim([tvd.max(), tvd.min()])
else:
raise Exception("Kind must be MD or TVD")
for sp in ax.spines.values():
sp.set_color('gray')
if ax.is_first_col():
pad = -10
ax.spines['left'].set_color('none')
ax.yaxis.set_ticks_position('right')
for label in ax.get_yticklabels():
label.set_horizontalalignment('right')
elif ax.is_last_col(): | python | {
"resource": ""
} |
q21917 | Well.survey_basis | train | def survey_basis(self, keys=None, alias=None, step=None):
"""
Look at the basis of all the curves in ``well.data`` and return a
basis with the minimum start, maximum depth, and minimum step.
Args:
keys (list): List of strings: the keys of the data items to
survey, if not all of them.
alias (dict): a dictionary mapping mnemonics to lists of mnemonics.
step (float): a new step, if you want to change it.
Returns:
ndarray. The most complete common basis.
"""
if keys is None:
keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
else:
keys = utils.flatten_list(keys)
starts, stops, steps = [], [], []
for k in keys:
d = self.get_curve(k, alias=alias)
if keys and (d is None):
| python | {
"resource": ""
} |
q21918 | Well.get_mnemonics_from_regex | train | def get_mnemonics_from_regex(self, pattern):
"""
Should probably integrate getting curves with regex, vs getting with
aliases, even though mixing them is probably confusing. For now I can't
think of another use case for these wildcards, so I'll just implement
for the curve table and we can worry about a nice solution later if we
| python | {
"resource": ""
} |
q21919 | Well.get_mnemonic | train | def get_mnemonic(self, mnemonic, alias=None):
"""
Instead of picking curves by name directly from the data dict, you
can pick them up with this method, which takes account of the alias
dict you pass it. If you do not pass an alias dict, then you get the
curve you asked for, if it exists, or None. NB Wells do not have alias
dicts, but Projects do.
Args:
mnemonic (str): the name of the curve you want.
alias (dict): an alias dictionary, mapping mnemonics to lists of | python | {
"resource": ""
} |
q21920 | Well.get_curve | train | def get_curve(self, mnemonic, alias=None):
"""
Wraps get_mnemonic.
Instead of picking curves by name directly from the data dict, you
can pick them up with this method, which takes account of the alias
dict you pass it. If you do not pass an alias dict, then you get the
curve you asked for, if it exists, or None. NB Wells do not have alias
dicts, but Projects do.
Args:
mnemonic (str): the name of the curve you want.
| python | {
"resource": ""
} |
q21921 | Well.count_curves | train | def count_curves(self, keys=None, alias=None):
"""
Counts the number of curves in the well that will be selected with the
given key list and the given alias dict. Used by Project's curve table.
"""
if keys is None:
| python | {
"resource": ""
} |
q21922 | Well.make_synthetic | train | def make_synthetic(self,
srd=0,
v_repl_seismic=2000,
v_repl_log=2000,
f=50,
dt=0.001):
"""
Early hack. Use with extreme caution.
Hands-free. There'll be a more granualr version in synthetic.py.
Assumes DT is in µs/m and RHOB is kg/m3.
There is no handling yet for TVD.
The datum handling is probably sketchy.
TODO:
A lot.
"""
kb = getattr(self.location, 'kb', None) or 0
data0 = self.data['DT'].start
log_start_time = ((srd - kb) / v_repl_seismic) + (data0 / v_repl_log)
# Basic log values.
dt_log = self.data['DT'].despike() # assume µs/m
rho_log = self.data['RHOB'].despike() # assume kg/m3
if not np.allclose(dt_log.basis, rho_log.basis):
rho_log = rho_log.to_basis_like(dt_log)
Z = (1e6 / dt_log) * rho_log
# Two-way-time.
scaled_dt = dt_log.step * np.nan_to_num(dt_log) / 1e6
twt = 2 * np.cumsum(scaled_dt)
t = twt + log_start_time
# Move to time.
| python | {
"resource": ""
} |
q21923 | Well.qc_curve_group | train | def qc_curve_group(self, tests, alias=None):
"""
Run tests on a cohort of curves.
Args:
alias (dict): an alias dictionary, mapping mnemonics to lists of
mnemonics.
Returns:
dict.
"""
keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
if not keys:
return {}
| python | {
"resource": ""
} |
q21924 | Well.qc_data | train | def qc_data(self, tests, alias=None):
"""
Run a series of tests against the data and return the corresponding
results.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# We'll get a result for each curve here. | python | {
"resource": ""
} |
q21925 | Well.data_as_matrix | train | def data_as_matrix(self,
keys=None,
return_basis=False,
basis=None,
alias=None,
start=None,
stop=None,
step=None,
window_length=None,
window_step=1,
):
"""
Provide a feature matrix, given a list of data items.
I think this will probably fail if there are striplogs in the data
dictionary for this well.
TODO:
Deal with striplogs and other data, if present.
Args:
keys (list): List of the logs to export from the data dictionary.
return_basis (bool): Whether or not to return the basis that was
used.
basis (ndarray): The basis to use. Default is to survey all curves
to find a common basis.
alias (dict): A mapping of alias names to lists of mnemonics.
start (float): Optionally override the start of whatever basis
you find or (more likely) is surveyed.
stop (float): Optionally override the stop of whatever basis
you find or (more likely) is surveyed.
step (float): Override the step in the basis from survey_basis.
window_length (int): The number of samples to return around each sample.
This will provide one or more shifted versions of the features.
window_step (int): How much to step the offset versions.
Returns:
ndarray.
or
ndarray, ndarray if return_basis=True
"""
if keys is None:
keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
else:
# Only look at the alias list if keys were passed.
if alias is not None:
_keys = []
for k in keys:
if k in alias:
added = False
for a in alias[k]:
if a in self.data:
_keys.append(a)
added = True
break
if not added:
_keys.append(k)
else:
_keys.append(k)
keys = _keys
if basis is None:
basis = self.survey_basis(keys=keys, step=step)
# Get the data, or None is curve is missing.
data = [self.data.get(k) for k in | python | {
"resource": ""
} |
q21926 | CRS.from_string | train | def from_string(cls, prjs):
"""
Turn a PROJ.4 string into a mapping of parameters. Bare parameters
like "+no_defs" are given a value of ``True``. All keys are checked
against the ``all_proj_keys`` list.
Args:
prjs (str): A PROJ4 string.
"""
def parse(v):
| python | {
"resource": ""
} |
q21927 | similarity_by_path | train | def similarity_by_path(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float:
"""
Returns maximum path similarity between two senses.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch').
:return: A float, similarity measurement.
"""
if option.lower() in ["path", "path_similarity"]: # Path similarities.
return max(wn.path_similarity(sense1, sense2, if_none_return=0),
wn.path_similarity(sense2, sense1, if_none_return=0))
| python | {
"resource": ""
} |
q21928 | similarity_by_infocontent | train | def similarity_by_infocontent(sense1: "wn.Synset", sense2: "wn.Synset", option: str) -> float:
"""
Returns similarity scores by information content.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('res', 'jcn', 'lin').
:return: A float, similarity measurement.
"""
if sense1.pos != sense2.pos: # infocontent sim can't do diff POS.
return 0
if option in ['res', 'resnik']:
if sense1.pos not in wnic_bnc_resnik_add1.ic:
return 0
return wn.res_similarity(sense1, sense2, wnic_bnc_resnik_add1)
#return min(wn.res_similarity(sense1, sense2, wnic.ic(ic)) \
# for | python | {
"resource": ""
} |
q21929 | sim | train | def sim(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float:
"""
Calculates similarity based on user's choice.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin').
:return: A float, similarity measurement.
"""
option = option.lower()
if option.lower() in ["path", "path_similarity",
"wup", "wupa", "wu-palmer", "wu-palmer",
| python | {
"resource": ""
} |
q21930 | lemmatize | train | def lemmatize(ambiguous_word: str, pos: str = None, neverstem=False,
lemmatizer=wnl, stemmer=porter) -> str:
"""
Tries to convert a surface word into lemma, and if lemmatize word is not in
wordnet then try and convert surface word into its stem.
This is to handle the case where users input a surface word as an ambiguous
word and the surface word is a not a lemma.
"""
# Try to be a little smarter and use most frequent POS.
pos = pos if pos else penn2morphy(pos_tag([ambiguous_word])[0][1],
| python | {
"resource": ""
} |
q21931 | has_synset | train | def has_synset(word: str) -> list:
"""" Returns a list of synsets of a word after lemmatization. """
| python | {
"resource": ""
} |
q21932 | LinearClassifier.get_label | train | def get_label(self, x, w):
"""
Computes the label for each data point
"""
| python | {
"resource": ""
} |
q21933 | LinearClassifier.add_intercept_term | train | def add_intercept_term(self, x):
"""
Adds a column of ones to estimate the intercept term for
separation boundary
"""
nr_x,nr_f = x.shape
| python | {
"resource": ""
} |
q21934 | LinearClassifier.evaluate | train | def evaluate(self, truth, predicted):
"""
Evaluates the predicted outputs against the gold data.
"""
correct = 0.0
total = 0.0
for i in range(len(truth)):
| python | {
"resource": ""
} |
q21935 | synset_signatures | train | def synset_signatures(ss: "wn.Synset", hyperhypo=True, adapted=False,
remove_stopwords=True, to_lemmatize=True, remove_numbers=True,
lowercase=True, original_lesk=False, from_cache=True) -> set:
"""
Takes a Synset and returns its signature words.
:param ss: An instance of wn.Synset.
:return: A set of signature strings
"""
if from_cache:
return synset_signatures_from_cache(ss, hyperhypo, adapted, original_lesk)
# Collects the signatures from WordNet.
signature = []
# Adds the definition, example sentences and lemma_names.
signature += word_tokenize(ss.definition())
# If the original lesk signature is requested, skip the other signatures.
if original_lesk:
return set(signature)
# Adds the examples and lemma names.
signature += chain(*[word_tokenize(eg) for eg in ss.examples()])
signature += ss.lemma_names()
# Includes lemma_names of hyper-/hyponyms.
if hyperhypo:
hyperhyponyms = set(ss.hyponyms() + ss.hypernyms() + ss.instance_hyponyms() + ss.instance_hypernyms())
signature += set(chain(*[i.lemma_names() for i in hyperhyponyms]))
# Includes signatures from related senses as in Adapted Lesk.
if adapted:
# Includes lemma_names from holonyms, meronyms and similar_tos
related_senses = set(ss.member_holonyms() + ss.part_holonyms() + ss.substance_holonyms() + \
ss.member_meronyms() + ss.part_meronyms() + ss.substance_meronyms() + \
| python | {
"resource": ""
} |
q21936 | signatures | train | def signatures(ambiguous_word: str, pos: str = None, hyperhypo=True, adapted=False,
remove_stopwords=True, to_lemmatize=True, remove_numbers=True,
lowercase=True, to_stem=False, original_lesk=False, from_cache=True) -> dict:
"""
Takes an ambiguous word and optionally its Part-Of-Speech and returns
a dictionary where keys are the synsets and values are sets of signatures.
:param ambiguous_word: String, a single word.
:param pos: String, one of 'a', 'r', 's', 'n', 'v', or None.
:return: dict(synset:{signatures}).
"""
# Ensure that the POS is supported.
pos = pos if pos in ['a', 'r', 's', 'n', 'v', None] else None
# If the POS specified isn't found but other POS is in wordnet.
if not wn.synsets(ambiguous_word, pos) and wn.synsets(ambiguous_word):
pos = None
# Holds the synset->signature dictionary.
ss_sign = {}
for ss in wn.synsets(ambiguous_word, pos):
ss_sign[ss] = synset_signatures(ss, hyperhypo=hyperhypo,
adapted=adapted,
| python | {
"resource": ""
} |
q21937 | compare_overlaps_greedy | train | def compare_overlaps_greedy(context: list, synsets_signatures: dict) -> "wn.Synset":
"""
Calculate overlaps between the context sentence and the synset_signatures
and returns the synset with the highest overlap.
Note: Greedy algorithm only keeps the best sense,
see https://en.wikipedia.org/wiki/Greedy_algorithm
Only used by original_lesk(). Keeping greedy algorithm for documentary sake,
because original_lesks is greedy.
:param context: List of strings, tokenized sentence or document.
:param synsets_signatures: dict of Synsets and the | python | {
"resource": ""
} |
q21938 | compare_overlaps | train | def compare_overlaps(context: list, synsets_signatures: dict,
nbest=False, keepscore=False, normalizescore=False) -> "wn.Synset":
"""
Calculates overlaps between the context sentence and the synset_signture
and returns a ranked list of synsets from highest overlap to lowest.
:param context: List of strings, tokenized sentence or document.
:param synsets_signatures: dict of Synsets and the set of their corresponding signatures.
:return: The Synset with the highest number of overlaps with its signatures.
"""
overlaplen_synsets = [] # a tuple of (len(overlap), synset).
for ss in synsets_signatures:
overlaps = set(synsets_signatures[ss]).intersection(context)
overlaplen_synsets.append((len(overlaps), ss))
# Rank synsets from highest to lowest overlap.
ranked_synsets = sorted(overlaplen_synsets, reverse=True)
| python | {
"resource": ""
} |
q21939 | SemEval2007_Coarse_WSD.fileids | train | def fileids(self):
""" Returns files from SemEval2007 Coarse-grain All-words WSD task. """
| python | {
"resource": ""
} |
q21940 | SemEval2007_Coarse_WSD.sents | train | def sents(self, filename=None):
"""
Returns the file, line by line. Use test_file if no filename specified.
| python | {
"resource": ""
} |
q21941 | SemEval2007_Coarse_WSD.sentences | train | def sentences(self):
"""
Returns the instances by sentences, and yields a list of tokens,
similar to the pywsd.semcor.sentences.
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> for sent in coarse_wsd.sentences():
>>> for token in sent:
>>> print token
>>> break
>>> break
word(id=None, text=u'Your', offset=None, sentid=0, paraid=u'd001', term=None)
"""
for sentid, ys in enumerate(self.yield_sentences()):
sent, context_sent, context_doc, inst2ans, textid = ys
instances = {}
for instance in sent.findAll('instance'):
instid = instance['id']
lemma = instance['lemma']
word = instance.text
instances[instid] = Instance(instid, lemma, word)
tokens = []
for i in sent: # Iterates through BeautifulSoup object.
if str(i).startswith('<instance'): # BeautifulSoup.Tag
| python | {
"resource": ""
} |
q21942 | random_sense | train | def random_sense(ambiguous_word: str, pos=None) -> "wn.Synset":
"""
Returns a random sense.
:param ambiguous_word: String, a single word.
:param pos: String, one of 'a', 'r', 's', 'n', 'v', or None.
:return: A random Synset.
"""
if pos is None:
| python | {
"resource": ""
} |
q21943 | first_sense | train | def first_sense(ambiguous_word: str, pos: str = None) -> "wn.Synset":
"""
Returns the first sense.
:param ambiguous_word: String, a single word.
:param pos: String, one of 'a', 'r', 's', 'n', 'v', or None.
:return: The first | python | {
"resource": ""
} |
q21944 | estimate_gaussian | train | def estimate_gaussian(X):
"""
Returns the mean and the variance of a data set of X points assuming that
the points come from a gaussian distribution X.
| python | {
"resource": ""
} |
q21945 | dict_max | train | def dict_max(dic):
"""
Returns maximum value of a dictionary.
"""
aux = dict(map(lambda item: (item[1],item[0]),dic.items()))
if aux.keys() == []:
| python | {
"resource": ""
} |
q21946 | l2norm_squared | train | def l2norm_squared(a):
"""
L2 normalize squared
"""
value = 0
for i in xrange(a.shape[1]):
| python | {
"resource": ""
} |
q21947 | KNNIndex.check_metric | train | def check_metric(self, metric):
"""Check that the metric is supported by the KNNIndex instance."""
if metric not in self.VALID_METRICS:
raise ValueError(
f"`{self.__class__.__name__}` does not support the `{metric}` "
| python | {
"resource": ""
} |
q21948 | random | train | def random(X, n_components=2, random_state=None):
"""Initialize an embedding using samples from an isotropic Gaussian.
Parameters
----------
X: np.ndarray
The data matrix.
n_components: int
The dimension of the embedding space.
random_state: Union[int, RandomState]
If the value is an int, | python | {
"resource": ""
} |
q21949 | pca | train | def pca(X, n_components=2, random_state=None):
"""Initialize an embedding using the top principal components.
Parameters
----------
X: np.ndarray
The data matrix.
n_components: int
The dimension of the embedding space.
random_state: Union[int, RandomState]
If the value is an int, random_state is the seed used by the random
number generator. If the value is a RandomState instance, then it will
be used as the random number generator. If the value is None, the random
number generator is the RandomState instance used by `np.random`.
Returns
-------
initialization: np.ndarray
""" | python | {
"resource": ""
} |
q21950 | weighted_mean | train | def weighted_mean(X, embedding, neighbors, distances):
"""Initialize points onto an existing embedding by placing them in the
weighted mean position of their nearest neighbors on the reference embedding.
Parameters
----------
X: np.ndarray
embedding: TSNEEmbedding
neighbors: np.ndarray
distances: np.ndarray
Returns
-------
np.ndarray
"""
| python | {
"resource": ""
} |
q21951 | make_heap_initializer | train | def make_heap_initializer(dist, dist_args):
"""Create a numba accelerated version of heap initialization for the
alternative k-neighbor graph algorithm. This approach builds two heaps
of neighbors simultaneously, one is a heap used to construct a very
approximate k-neighbor graph for searching; the other is the
initialization for searching.
Parameters
----------
dist: function
A numba JITd distance function which, given two arrays computes a
dissimilarity between them.
dist_args: tuple
Any extra arguments that need to be passed to the distance function
beyond the two arrays to be compared.
Returns
-------
A numba JITd function for for heap initialization that is
specialised to the given metric.
"""
@numba.njit(parallel=True)
def initialize_heaps(data, n_neighbors, leaf_array):
graph_heap = make_heap(data.shape[0], 10)
| python | {
"resource": ""
} |
q21952 | degree_prune | train | def degree_prune(graph, max_degree=20):
"""Prune the k-neighbors graph back so that nodes have a maximum
degree of ``max_degree``.
Parameters
----------
graph: sparse matrix
The adjacency matrix of the graph
max_degree: int (optional, default 20)
The maximum degree of any node in the pruned graph
Returns
-------
result: sparse matrix
The pruned graph.
"""
result = graph.tolil()
for i, row_data in enumerate(result.data):
if len(row_data) > max_degree:
| python | {
"resource": ""
} |
q21953 | NNDescent.query | train | def query(self, query_data, k=10, queue_size=5.0):
"""Query the training data for the k nearest neighbors
Parameters
----------
query_data: array-like, last dimension self.dim
An array of points to query
k: integer (default = 10)
The number of nearest neighbors to return
queue_size: float (default 5.0)
The multiplier of the internal search queue. This controls the
speed/accuracy tradeoff. Low values will search faster but with
more approximate results. High values will search more
accurately, but will require more computation to do so. Values
should generally be in the range 1.0 to 10.0.
Returns
-------
indices, distances: array (n_query_points, k), array (n_query_points, k)
The first array, ``indices``, provides the indices of the data
points in the training set that are the nearest neighbors of
each query point. Thus ``indices[i, j]`` is the index into the
training data of the jth nearest neighbor of the ith query points.
Similarly ``distances`` provides the distances to the neighbors
of the query points such that ``distances[i, j]`` is the distance
| python | {
"resource": ""
} |
q21954 | PyNNDescentTransformer.fit | train | def fit(self, X):
"""Fit the PyNNDescent transformer to build KNN graphs with
neighbors given by the dataset X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Sample data
Returns
-------
transformer : PyNNDescentTransformer
The trained transformer
"""
self.n_samples_fit = X.shape[0]
| python | {
"resource": ""
} |
q21955 | weighted_minkowski | train | def weighted_minkowski(x, y, w=_mock_identity, p=2):
"""A weighted version of Minkowski distance.
..math::
D(x, y) = \left(\sum_i w_i |x_i - y_i|^p\right)^{\frac{1}{p}}
If weights w_i are inverse standard deviations of data in each dimension
then this represented a standardised Minkowski distance | python | {
"resource": ""
} |
q21956 | _handle_nice_params | train | def _handle_nice_params(optim_params: dict) -> None:
"""Convert the user friendly params into something the optimizer can
understand."""
# Handle callbacks
optim_params["callbacks"] = _check_callbacks(optim_params.get("callbacks"))
optim_params["use_callbacks"] = optim_params["callbacks"] is not None
# Handle negative gradient method
negative_gradient_method = optim_params.pop("negative_gradient_method")
if callable(negative_gradient_method):
negative_gradient_method = negative_gradient_method
elif negative_gradient_method in {"bh", "BH", "barnes-hut"}:
negative_gradient_method = kl_divergence_bh
elif negative_gradient_method in {"fft", "FFT", "interpolation"}:
negative_gradient_method | python | {
"resource": ""
} |
q21957 | PartialTSNEEmbedding.optimize | train | def optimize(self, n_iter, inplace=False, propagate_exception=False,
**gradient_descent_params):
"""Run optmization on the embedding for a given number of steps.
Parameters
----------
n_iter: int
The number of optimization iterations.
learning_rate: float
The learning rate for t-SNE optimization. Typical values range
between 100 to 1000. Setting the learning rate too low or too high
may result in the points forming a "ball". This is also known as the
crowding problem.
exaggeration: float
The exaggeration factor is used to increase the attractive forces of
nearby points, producing more compact clusters.
momentum: float
Momentum accounts for gradient directions from previous iterations,
resulting in faster convergence.
negative_gradient_method: str
Specifies the negative gradient approximation method to use. For
smaller data sets, the Barnes-Hut approximation is appropriate and
can be set using one of the following aliases: ``bh``, ``BH`` or
``barnes-hut``. For larger data sets, the FFT accelerated
interpolation method is more appropriate and can be set using one of
the following aliases: ``fft``, ``FFT`` or ``ìnterpolation``.
theta: float
This is the trade-off parameter between speed and accuracy of the
tree approximation method. Typical values range from 0.2 to 0.8. The
value 0 indicates that no approximation is to be made and produces
exact results also producing longer runtime.
n_interpolation_points: int
Only used when ``negative_gradient_method="fft"`` or its other
aliases. The number of interpolation points to use within each grid
cell for interpolation based t-SNE. It is highly recommended leaving
this value at the default 3.
min_num_intervals: int
Only used when ``negative_gradient_method="fft"`` or its other
aliases. The minimum number of grid cells to use, regardless of the
``ints_in_interval`` parameter. Higher values provide more accurate
| python | {
"resource": ""
} |
q21958 | TSNEEmbedding.transform | train | def transform(self, X, perplexity=5, initialization="median", k=25,
learning_rate=1, n_iter=100, exaggeration=2, momentum=0):
"""Embed new points into the existing embedding.
This procedure optimizes each point only with respect to the existing
embedding i.e. it ignores any interactions between the points in ``X``
among themselves.
Please see the :ref:`parameter-guide` for more information.
Parameters
----------
X: np.ndarray
The data matrix to be added to the existing embedding.
perplexity: float
Perplexity can be thought of as the continuous :math:`k` number of
nearest neighbors, for which t-SNE will attempt to preserve
distances. However, when transforming, we only consider neighbors in
the existing embedding i.e. each data point is placed into the
embedding, independently of other new data points.
initialization: Union[np.ndarray, str]
The initial point positions to be used in the embedding space. Can
be a precomputed numpy array, ``median``, ``weighted`` or
``random``. In all cases, ``median`` of ``weighted`` should be
preferred.
k: int
The number of nearest neighbors to consider when initially placing
the point onto the embedding. This is different from ``perpelxity``
because perplexity affects optimization while this only affects the
initial point positions.
learning_rate: float
The learning rate for t-SNE optimization. Typical values range
between 100 to 1000. Setting the learning rate too low or too high
may result in the points forming a "ball". This is also known as the
crowding problem.
n_iter: int
The number of iterations to run in the normal optimization regime.
Typically, the number of iterations needed when adding new data
points is much lower than with regular optimization.
exaggeration: float
The exaggeration factor to use during the normal optimization phase.
This can be used to form more densely packed clusters and is useful
for large data sets.
momentum: float
The momentum to use during optimization phase.
Returns
| python | {
"resource": ""
} |
q21959 | TSNEEmbedding.prepare_partial | train | def prepare_partial(self, X, initialization="median", k=25, **affinity_params):
"""Prepare a partial embedding which can be optimized.
Parameters
----------
X: np.ndarray
The data matrix to be added to the existing embedding.
initialization: Union[np.ndarray, str]
The initial point positions to be used in the embedding space. Can
be a precomputed numpy array, ``median``, ``weighted`` or
``random``. In all cases, ``median`` of ``weighted`` should be
preferred.
k: int
The number of nearest neighbors to consider when initially placing
the point onto the embedding. This is different from ``perpelxity``
because perplexity affects optimization while this only affects the
initial point positions.
**affinity_params: dict
Additional params to be passed to the ``Affinities.to_new`` method.
Please see individual :class:`~openTSNE.affinity.Affinities`
implementations as the parameters differ between implementations.
Returns
-------
PartialTSNEEmbedding
An unoptimized :class:`PartialTSNEEmbedding` object, prepared for
optimization.
"""
P, neighbors, distances = self.affinities.to_new(
X, return_distances=True, **affinity_params
)
# If initial positions are given in an array, use a copy | python | {
"resource": ""
} |
q21960 | TSNE.fit | train | def fit(self, X):
"""Fit a t-SNE embedding for a given data set.
Runs the standard t-SNE optimization, consisting of the early
exaggeration phase and a normal optimization phase.
Parameters
----------
X: np.ndarray
The data matrix to be embedded.
Returns
-------
TSNEEmbedding
A fully optimized t-SNE embedding.
"""
embedding = self.prepare_initial(X)
try:
# Early exaggeration with lower momentum to allow points to find more
# easily move around and find their neighbors
embedding.optimize(
n_iter=self.early_exaggeration_iter,
exaggeration=self.early_exaggeration,
momentum=self.initial_momentum,
inplace=True,
propagate_exception=True,
)
# Restore actual affinity probabilities and increase momentum to get
| python | {
"resource": ""
} |
q21961 | TSNE.prepare_initial | train | def prepare_initial(self, X):
"""Prepare the initial embedding which can be optimized as needed.
Parameters
----------
X: np.ndarray
The data matrix to be embedded.
Returns
-------
TSNEEmbedding
An unoptimized :class:`TSNEEmbedding` object, prepared for
optimization.
"""
# If initial positions are given in an array, use a copy of that
if isinstance(self.initialization, np.ndarray):
init_checks.num_samples(self.initialization.shape[0], X.shape[0])
init_checks.num_dimensions(self.initialization.shape[1], self.n_components)
embedding = np.array(self.initialization)
variance = np.var(embedding, axis=0)
if any(variance > 1e-4):
log.warning(
"Variance of embedding is greater than 0.0001. Initial "
"embeddings with high variance may have display poor convergence."
)
elif self.initialization == "pca":
embedding = initialization_scheme.pca(
X, self.n_components, random_state=self.random_state
)
elif self.initialization == "random":
embedding = initialization_scheme.random(
X, self.n_components, random_state=self.random_state
)
else:
raise ValueError(
f"Unrecognized initialization scheme `{self.initialization}`."
)
affinities = PerplexityBasedNN(
X,
self.perplexity,
method=self.neighbors_method,
metric=self.metric,
metric_params=self.metric_params,
n_jobs=self.n_jobs,
random_state=self.random_state,
)
gradient_descent_params = {
# Degrees of freedom of the Student's t-distribution. The
# suggestion degrees_of_freedom = n_components - 1 | python | {
"resource": ""
} |
q21962 | PerplexityBasedNN.set_perplexity | train | def set_perplexity(self, new_perplexity):
"""Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighbors, which
can take a long time. To avoid potential confusion as to why execution
time is slow, this is not allowed. If you would like to increase the
perplexity above the initial value, simply create a new instance.
Parameters
----------
new_perplexity: float
The new perplexity.
"""
# If the value hasn't changed, there's nothing to do
if new_perplexity == self.perplexity:
return
# Verify that the perplexity isn't too large
new_perplexity = self.check_perplexity(new_perplexity)
# Recompute the affinity matrix
k_neighbors = min(self.n_samples - 1, int(3 * new_perplexity))
if k_neighbors > self.__neighbors.shape[1]:
raise RuntimeError(
"The desired perplexity `%.2f` is larger than the initial one "
| python | {
"resource": ""
} |
q21963 | MultiscaleMixture.set_perplexities | train | def set_perplexities(self, new_perplexities):
"""Change the perplexities of the affinity matrix.
Note that we only allow lowering the perplexities or restoring them to
their original maximum value. This restriction exists because setting a
higher perplexity value requires recomputing all the nearest neighbors,
which can take a long time. To avoid potential confusion as to why
execution time is slow, this is not allowed. If you would like to
increase the perplexity above the initial value, simply create a new
instance.
Parameters
----------
new_perplexities: List[float]
The new list of perplexities.
"""
if np.array_equal(self.perplexities, new_perplexities):
return
new_perplexities = self.check_perplexities(new_perplexities)
max_perplexity = np.max(new_perplexities)
k_neighbors = min(self.n_samples - 1, int(3 * max_perplexity))
if k_neighbors > self.__neighbors.shape[1]:
raise RuntimeError(
"The largest perplexity `%.2f` is larger than the initial one "
| python | {
"resource": ""
} |
q21964 | euclidean_random_projection_split | train | def euclidean_random_projection_split(data, indices, rng_state):
"""Given a set of ``indices`` for data points from ``data``, create
a random hyperplane to split the data, returning two arrays indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simply uses this splitting recursively.
This particular split uses euclidean distance to determine the hyperplane
and which side each data sample falls on.
Parameters
----------
data: array of shape (n_samples, n_features)
The original data to be split
indices: array of shape (tree_node_size,)
The indices of the elements in the ``data`` array that are to
be split in the current operation.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
indices_left: array
The elements of ``indices`` that fall on the "left" side of the
random hyperplane.
indices_right: array
The elements of ``indices`` that fall on the "left" side of the
random hyperplane.
"""
dim = data.shape[1]
# Select two random points, set the hyperplane between them
left_index = tau_rand_int(rng_state) % indices.shape[0]
right_index = tau_rand_int(rng_state) % indices.shape[0]
right_index += left_index == right_index
right_index = right_index % indices.shape[0]
left = indices[left_index]
right = indices[right_index]
# Compute the normal vector to the hyperplane (the vector between
# the two points) and the offset from the origin
hyperplane_offset = 0.0
hyperplane_vector = np.empty(dim, dtype=np.float32)
for d in range(dim):
hyperplane_vector[d] = data[left, d] - data[right, d]
hyperplane_offset -= (
hyperplane_vector[d] * (data[left, d] + data[right, d]) / 2.0
)
| python | {
"resource": ""
} |
q21965 | get_acf | train | def get_acf(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param axis: (optional)
The time axis of ``x``. Assumed to be the first axis if not specified.
:param fast: (optional)
If ``True``, only use the largest ``2^n`` entries for efficiency.
(default: False)
"""
x = np.atleast_1d(x)
m = [slice(None), ] * len(x.shape)
# For computational efficiency, crop the chain to the largest power of
# two if requested.
if fast:
| python | {
"resource": ""
} |
q21966 | get_integrated_act | train | def get_integrated_act(x, axis=0, window=50, fast=False):
"""
Estimate the integrated autocorrelation time of a time series.
See `Sokal's notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ on
MCMC and sample estimators for autocorrelation times.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param axis: (optional)
The time axis of ``x``. Assumed to be the first axis if not specified.
:param window: (optional)
The size of the window to use. (default: 50)
:param fast: (optional)
If ``True``, only | python | {
"resource": ""
} |
q21967 | thermodynamic_integration_log_evidence | train | def thermodynamic_integration_log_evidence(betas, logls):
"""
Thermodynamic integration estimate of the evidence.
:param betas: The inverse temperatures to use for the quadrature.
:param logls: The mean log-likelihoods corresponding to ``betas`` to use for
computing the thermodynamic evidence.
:return ``(logZ, dlogZ)``: Returns an estimate of the
log-evidence and the error associated with the finite
number of temperatures at which the posterior has been
sampled.
The evidence is the integral of the un-normalized posterior
over all of parameter space:
.. math::
Z \\equiv \\int d\\theta \\, l(\\theta) p(\\theta)
Thermodymanic integration is a technique for estimating the
evidence integral using information from the chains at various
temperatures. Let
.. math::
Z(\\beta) = \\int d\\theta \\, l^\\beta(\\theta) p(\\theta)
Then
.. math::
\\frac{d \\log Z}{d \\beta}
= \\frac{1}{Z(\\beta)} \\int d\\theta l^\\beta p \\log l
= \\left \\langle \\log l \\right \\rangle_\\beta
so
.. math::
\\log Z(1) - \\log Z(0)
= \\int_0^1 d\\beta \\left \\langle \\log l \\right\\rangle_\\beta
By computing the average of the log-likelihood at the
difference temperatures, the sampler can approximate the above
integral.
"""
| python | {
"resource": ""
} |
q21968 | find_frequent_patterns | train | def find_frequent_patterns(transactions, support_threshold):
"""
Given a set of transactions, find the patterns in it
over the specified support threshold.
"""
| python | {
"resource": ""
} |
q21969 | FPNode.has_child | train | def has_child(self, value):
"""
Check if node has a particular child node.
| python | {
"resource": ""
} |
q21970 | FPNode.get_child | train | def get_child(self, value):
"""
Return a child node with a particular value.
| python | {
"resource": ""
} |
q21971 | FPNode.add_child | train | def add_child(self, value):
"""
Add a node as a child node.
"""
child | python | {
"resource": ""
} |
q21972 | FPTree.find_frequent_items | train | def find_frequent_items(transactions, threshold):
"""
Create a dictionary of items with occurrences above the threshold.
"""
items = {}
for transaction in transactions:
for item in transaction:
if item in items:
items[item] += 1
| python | {
"resource": ""
} |
q21973 | FPTree.build_fptree | train | def build_fptree(self, transactions, root_value,
root_count, frequent, headers):
"""
Build the FP tree and return the root node.
"""
root = FPNode(root_value, root_count, None)
for transaction in transactions:
sorted_items = [x for x in transaction if x in | python | {
"resource": ""
} |
q21974 | FPTree.insert_tree | train | def insert_tree(self, items, node, headers):
"""
Recursively grow FP tree.
"""
first = items[0]
child = node.get_child(first)
if child is not None:
child.count += 1
else:
# Add new child.
child = node.add_child(first)
# Link it to header structure.
if headers[first] is None:
headers[first] = child
else:
| python | {
"resource": ""
} |
q21975 | FPTree.tree_has_single_path | train | def tree_has_single_path(self, node):
"""
If there is a single path in the tree,
return True, else return False.
"""
num_children = len(node.children)
if num_children > 1:
return False
| python | {
"resource": ""
} |
q21976 | FPTree.mine_patterns | train | def mine_patterns(self, threshold):
"""
Mine the constructed FP tree for frequent patterns.
"""
if self.tree_has_single_path(self.root):
| python | {
"resource": ""
} |
q21977 | FPTree.zip_patterns | train | def zip_patterns(self, patterns):
"""
Append suffix to patterns in dictionary if
we are in a conditional FP tree.
"""
suffix = self.root.value
if suffix is not None:
# We are in a conditional tree.
| python | {
"resource": ""
} |
q21978 | FPTree.generate_pattern_list | train | def generate_pattern_list(self):
"""
Generate a list of patterns with support counts.
"""
patterns = {}
items = self.frequent.keys()
# If we are in a conditional tree,
# the suffix is a pattern on its own.
if self.root.value is None:
suffix_value = []
else:
suffix_value = [self.root.value]
patterns[tuple(suffix_value)] = self.root.count
for i in range(1, len(items) + 1):
| python | {
"resource": ""
} |
q21979 | FPTree.mine_sub_trees | train | def mine_sub_trees(self, threshold):
"""
Generate subtrees and mine them for patterns.
"""
patterns = {}
mining_order = sorted(self.frequent.keys(),
key=lambda x: self.frequent[x])
# Get items in tree in reverse order of occurrences.
for item in mining_order:
suffixes = []
conditional_tree_input = []
node = self.headers[item]
# Follow node links to get a list of
# all occurrences of a certain item.
while node is not None:
suffixes.append(node)
node = node.link
# For each occurrence of the item,
# trace the path back to the root node.
for suffix in suffixes:
frequency = suffix.count
path = []
parent = suffix.parent
while parent.parent is not None:
path.append(parent.value)
| python | {
"resource": ""
} |
q21980 | rm_subtitles | train | def rm_subtitles(path):
""" delete all subtitles in path recursively
"""
sub_exts = ['ass', 'srt', 'sub']
count = 0
for root, dirs, files in os.walk(path):
for f in files: | python | {
"resource": ""
} |
q21981 | mv_videos | train | def mv_videos(path):
""" move videos in sub-directory of path to path.
"""
count = 0
for f in os.listdir(path):
f = os.path.join(path, f)
if os.path.isdir(f):
for sf in os.listdir(f):
sf = os.path.join(f, sf)
if os.path.isfile(sf):
new_name = os.path.join(path, os.path.basename(sf))
try:
os.rename(sf, new_name)
| python | {
"resource": ""
} |
q21982 | ZimukuSubSearcher._get_subinfo_list | train | def _get_subinfo_list(self, videoname):
""" return subinfo_list of videoname
"""
# searching subtitles
res = self.session.get(self.API, params={'q': videoname})
doc = res.content
referer = res.url
subgroups = self._parse_search_results_html(doc)
if not subgroups:
return []
subgroup = self._filter_subgroup(subgroups)
# get subtitles
headers = {
'Referer': referer
}
| python | {
"resource": ""
} |
q21983 | register_subsearcher | train | def register_subsearcher(name, subsearcher_cls):
""" register a subsearcher, the `name` is a key used for searching subsearchers.
if the subsearcher named `name` already exists, then it's will overrite the old subsearcher.
"""
if not | python | {
"resource": ""
} |
q21984 | BaseSubSearcher._get_videoname | train | def _get_videoname(cls, videofile):
"""parse the `videofile` and return it's basename
"""
| python | {
"resource": ""
} |
q21985 | connect | train | def connect(
database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any
) -> Connection:
"""Create and return a connection proxy to the sqlite database."""
if loop is None:
loop = asyncio.get_event_loop()
def connector() -> sqlite3.Connection:
if isinstance(database, str):
loc = database
| python | {
"resource": ""
} |
q21986 | Cursor._execute | train | async def _execute(self, fn, *args, **kwargs):
"""Execute the given function on the shared connection's thread."""
| python | {
"resource": ""
} |
q21987 | Cursor.execute | train | async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
"""Execute the given query."""
if parameters is None:
| python | {
"resource": ""
} |
q21988 | Cursor.executemany | train | async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
| python | {
"resource": ""
} |
q21989 | Cursor.executescript | train | async def executescript(self, sql_script: str) -> None:
"""Execute a user script."""
| python | {
"resource": ""
} |
q21990 | Cursor.fetchone | train | async def fetchone(self) -> Optional[sqlite3.Row]:
| python | {
"resource": ""
} |
q21991 | Cursor.fetchmany | train | async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]:
"""Fetch up to `cursor.arraysize` number of rows.""" | python | {
"resource": ""
} |
q21992 | Cursor.fetchall | train | async def fetchall(self) -> Iterable[sqlite3.Row]:
"""Fetch all remaining rows."""
| python | {
"resource": ""
} |
q21993 | Connection.run | train | def run(self) -> None:
"""Execute function calls on a separate thread."""
while self._running:
try:
future, function = self._tx.get(timeout=0.1)
except Empty:
continue
try:
LOG.debug("executing %s", function)
result = function()
LOG.debug("returning %s", result)
| python | {
"resource": ""
} |
q21994 | Connection._execute | train | async def _execute(self, fn, *args, **kwargs):
"""Queue a function with the given arguments for execution."""
function = partial(fn, *args, **kwargs)
| python | {
"resource": ""
} |
q21995 | Connection._connect | train | async def _connect(self) -> "Connection":
"""Connect to the actual sqlite database."""
if self._connection is None:
| python | {
"resource": ""
} |
q21996 | Connection.cursor | train | async def cursor(self) -> Cursor:
"""Create an aiosqlite cursor wrapping a sqlite3 cursor object."""
| python | {
"resource": ""
} |
q21997 | Connection.execute_insert | train | async def execute_insert(
self, sql: str, parameters: Iterable[Any] = None
) -> Optional[sqlite3.Row]:
"""Helper to insert and get the last_insert_rowid."""
if parameters is None: | python | {
"resource": ""
} |
q21998 | Connection.execute_fetchall | train | async def execute_fetchall(
self, sql: str, parameters: Iterable[Any] = None
) -> Iterable[sqlite3.Row]:
"""Helper to execute a query and return all the data."""
if | python | {
"resource": ""
} |
q21999 | Connection.executemany | train | async def executemany(
self, sql: str, parameters: Iterable[Iterable[Any]]
) -> Cursor:
"""Helper to create a cursor and execute the given multiquery."""
cursor | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.