_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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. ...
python
{ "resource": "" }
q21901
Curve.interpolate
train
def interpolate(self): """ Interpolate across any missing zones. TODO Allow spline interpolation. """ nans, x = utils.nan_idx(self) self[nans] = np.interp(x(nans), x(~nans), self[~nans]) return self
python
{ "resource": "" }
q21902
Curve.interpolate_where
train
def interpolate_where(self, condition): """ Remove then interpolate across """ raise NotImplementedError() self[self < 0] = np.nan return self.interpolate()
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) index(bool) return_basis (bool) Returns: float or ndarray. """ try: ...
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 bo...
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. Def...
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. ...
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) return cls(param_dict) except: raise NotImplementedError
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. for e in ['log', 'card']: s...
python
{ "resource": "" }
q21909
Synthetic.basis
train
def basis(self): """ Compute basis rather than storing it. """ precision_adj = self.dt / 100 return np.arange(self.start, self.stop - precision_adj, self.dt)
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), 'mnemonic': 'SYN', 'step': 0.1524 ...
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. ...
python
{ "resource": "" }
q21912
no_gaps
train
def no_gaps(curve): """ Check for gaps, after ignoring any NaNs at the top and bottom. """ tnt = utils.top_and_tail(curve) return not any(np.isnan(tnt))
python
{ "resource": "" }
q21913
no_spikes
train
def no_spikes(tolerance): """ Arg ``tolerance`` is the number of spiky samples allowed. """ def no_spikes(curve): diff = np.abs(curve - curve.despike()) return np.count_nonzero(diff) < tolerance return no_spikes
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 'o...
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()``. ...
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. """ ...
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 su...
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 ...
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...
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 ...
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: keys = [k for k, v in self.data.items() if isinstance...
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 ...
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 isin...
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'...
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, ...
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(...
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 measureme...
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. ...
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 measureme...
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 inpu...
python
{ "resource": "" }
q21931
has_synset
train
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
python
{ "resource": "" }
q21932
LinearClassifier.get_label
train
def get_label(self, x, w): """ Computes the label for each data point """ scores = np.dot(x,w) return np.argmax(scores,axis=1).transpose()
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 intercept = np.ones([nr_x,1]) x = np.hstack((intercept,x)) return x
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)): if(truth[i] == predicted[i]): correct += 1 total += 1 return 1.0*corr...
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 in...
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-Sp...
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/Gre...
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...
python
{ "resource": "" }
q21939
SemEval2007_Coarse_WSD.fileids
train
def fileids(self): """ Returns files from SemEval2007 Coarse-grain All-words WSD task. """ return [os.path.join(self.path,i) for i in os.listdir(self.path)]
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. """ filename = filename if filename else self.test_file with io.open(filename, 'r') as fin: for line in fin: yield line.strip()
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 ...
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: return custom_random.choice(wn.synset...
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 Synset in the wn.synsets(word) list. """ if pos is None: ...
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. """ mean = np.mean(X,0) variance = np.var(X,0) return Gaussian(mean,variance)
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() == []: return 0 max_value = max(aux.keys()) return max_value,aux[max_value]
python
{ "resource": "" }
q21946
l2norm_squared
train
def l2norm_squared(a): """ L2 normalize squared """ value = 0 for i in xrange(a.shape[1]): value += np.dot(a[:,i],a[:,i]) return value
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}` " f"metric. Please choose one of the support...
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 ...
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...
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 ...
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 othe...
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 ...
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 ne...
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 : PyNNDescentTransform...
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 dista...
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 Non...
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:...
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 in...
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] ...
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. Re...
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` objec...
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 neighb...
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 al...
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 simpl...
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 axi...
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 multidime...
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...
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. """ tree = FPTree(transactions, support_threshold, None, None) return tree.mine_patterns(support_threshold)
python
{ "resource": "" }
q21969
FPNode.has_child
train
def has_child(self, value): """ Check if node has a particular child node. """ for node in self.children: if node.value == value: return True return False
python
{ "resource": "" }
q21970
FPNode.get_child
train
def get_child(self, value): """ Return a child node with a particular value. """ for node in self.children: if node.value == value: return node return None
python
{ "resource": "" }
q21971
FPNode.add_child
train
def add_child(self, value): """ Add a node as a child node. """ child = FPNode(value, 1, self) self.children.append(child) return 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 transacti...
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) ...
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 elif num_children == 0: return True else: ...
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): return self.generate_pattern_list() else: return self.zip_patterns(self.mine_sub_trees(threshold))
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. new_patterns = {} for key in patterns...
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_va...
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. ...
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: _, ext = os.path.splitext(f) ext = ext[1:] if ext in sub_exts: p = o...
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): ...
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 sub...
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 issubclass(subsearcher_cls, BaseSubSearcher): raise ValueError...
python
{ "resource": "" }
q21984
BaseSubSearcher._get_videoname
train
def _get_videoname(cls, videofile): """parse the `videofile` and return it's basename """ name = os.path.basename(videofile) name = os.path.splitext(name)[0] return name
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(dat...
python
{ "resource": "" }
q21986
Cursor._execute
train
async def _execute(self, fn, *args, **kwargs): """Execute the given function on the shared connection's thread.""" return await self._conn._execute(fn, *args, **kwargs)
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: parameters = [] await self._execute(self._cursor.execute, sql, parameters)
python
{ "resource": "" }
q21988
Cursor.executemany
train
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None: """Execute the given multiquery.""" await self._execute(self._cursor.executemany, sql, parameters)
python
{ "resource": "" }
q21989
Cursor.executescript
train
async def executescript(self, sql_script: str) -> None: """Execute a user script.""" await self._execute(self._cursor.executescript, sql_script)
python
{ "resource": "" }
q21990
Cursor.fetchone
train
async def fetchone(self) -> Optional[sqlite3.Row]: """Fetch a single row.""" return await self._execute(self._cursor.fetchone)
python
{ "resource": "" }
q21991
Cursor.fetchmany
train
async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]: """Fetch up to `cursor.arraysize` number of rows.""" args = () # type: Tuple[int, ...] if size is not None: args = (size,) return await self._execute(self._cursor.fetchmany, *args)
python
{ "resource": "" }
q21992
Cursor.fetchall
train
async def fetchall(self) -> Iterable[sqlite3.Row]: """Fetch all remaining rows.""" return await self._execute(self._cursor.fetchall)
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) ...
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) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future
python
{ "resource": "" }
q21995
Connection._connect
train
async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self
python
{ "resource": "" }
q21996
Connection.cursor
train
async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor))
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: parameters = [] return await self._execute(self._execute_insert, sql, parameters)
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 parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters)
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 = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor)
python
{ "resource": "" }