_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q30600
Encoder._get_codepage_char_map
train
def _get_codepage_char_map(self, encoding): """ Get codepage character map Process an encoding and return a map of UTF-characters to code points in this encoding. This is generated once only, and returned from a cache. :param encoding: The name of the encoding. """ ...
python
{ "resource": "" }
q30601
Encoder.can_encode
train
def can_encode(self, encoding, char): """Determine if a character is encodeable in the given code page. :param encoding: The name of the encoding. :param char: The character to attempt to encode. """
python
{ "resource": "" }
q30602
Encoder._encode_char
train
def _encode_char(char, charmap, defaultchar): """ Encode a single character with the given encoding map :param char: char to encode :param charmap: dictionary for mapping characters in this code page """ if ord(char) < 128:
python
{ "resource": "" }
q30603
Encoder.encode
train
def encode(self, text, encoding, defaultchar='?'): """ Encode text under the given encoding :param text: Text to encode :param encoding: Encoding name to use (must be defined in capabilities)
python
{ "resource": "" }
q30604
MagicEncode.force_encoding
train
def force_encoding(self, encoding): """Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page. """
python
{ "resource": "" }
q30605
MagicEncode.write
train
def write(self, text): """Write the text, automatically switching encodings. """ if self.disabled: self.write_with_encoding(self.encoding, text) return # See how far we can go into the text with the current encoding to_write, text = split_writable_text(s...
python
{ "resource": "" }
q30606
DocxTemplate.replace_media
train
def replace_media(self,src_file,dst_file): """Replace one media by another one into a docx This has been done mainly because it is not possible to add images in docx header/footer. With this function, put a dummy picture in your header/footer, then specify it with its replacemen...
python
{ "resource": "" }
q30607
DocxTemplate.replace_embedded
train
def replace_embedded(self,src_file,dst_file): """Replace one embdded object by another one into a docx This has been done mainly because it is not possible to add images in docx header/footer. With this function, put a dummy picture in your header/footer, then specify it with it...
python
{ "resource": "" }
q30608
DocxTemplate.build_pic_map
train
def build_pic_map(self): """Searches in docx template all the xml pictures tag and store them in pic_map dict""" if self.pic_to_replace: # Main document part=self.docx.part self.pic_map.update(self._img_filename_to_part(part)) # Header/Footer ...
python
{ "resource": "" }
q30609
ConstanceConfig.create_perm
train
def create_perm(self, using=None, *args, **kwargs): """ Creates a fake content type and permission to be able to check for permissions """ from django.conf import settings from django.contrib.auth.models import Permission from django.contrib.contenttypes.models im...
python
{ "resource": "" }
q30610
check_fieldsets
train
def check_fieldsets(*args, **kwargs): """ A Django system check to make sure that, if defined, CONFIG_FIELDSETS accounts for every entry in settings.CONFIG. """ if hasattr(settings, "CONFIG_FIELDSETS") and settings.CONFIG_FIELDSETS: inconsistent_fieldnames = get_inconsistent_fieldnames() ...
python
{ "resource": "" }
q30611
get_inconsistent_fieldnames
train
def get_inconsistent_fieldnames(): """ Returns a set of keys from settings.CONFIG that are not accounted for in settings.CONFIG_FIELDSETS. If there are no fieldnames in settings.CONFIG_FIELDSETS, returns an empty
python
{ "resource": "" }
q30612
FCMDeviceQuerySet.send_message
train
def send_message( self, title=None, body=None, icon=None, data=None, sound=None, badge=None, api_key=None, **kwargs): """ Send notification for all active devices in queryset and deactivate if ...
python
{ "resource": "" }
q30613
FCMDeviceQuerySet.send_data_message
train
def send_data_message( self, api_key=None, condition=None, collapse_key=None, delay_while_idle=False, time_to_live=None, restricted_package_name=None, low_priority=False, dry_run=False, data_message=N...
python
{ "resource": "" }
q30614
AbstractFCMDevice.send_message
train
def send_message( self, title=None, body=None, icon=None, data=None, sound=None, badge=None, api_key=None, **kwargs): """ Send single notification message. """ from .fcm import fcm...
python
{ "resource": "" }
q30615
AbstractFCMDevice.send_data_message
train
def send_data_message( self, condition=None, collapse_key=None, delay_while_idle=False, time_to_live=None, restricted_package_name=None, low_priority=False, dry_run=False, data_message=None, content_a...
python
{ "resource": "" }
q30616
sma
train
def sma(arg, n): """ If n is 0 then return the ltd mean; else return the n day mean """ if n == 0: return
python
{ "resource": "" }
q30617
rsi
train
def rsi(arg, n): """ compute RSI for the given arg arg: Series or DataFrame """ if isinstance(arg, pd.DataFrame): cols = [(name, rsi(arg[name], n)) for name in arg.columns] return pd.DataFrame.from_items(cols) else: assert isinstance(arg, pd.Series) n = int(n) ...
python
{ "resource": "" }
q30618
send_outlook_email
train
def send_outlook_email(to, subject, body, attachments=None, cc=None, bcc=None, is_html=0): """ Send an email using your local outlook client """ import win32com.client asarr = lambda v: None if not v else isinstance(v, basestring) and [v] or v def update_recipients(robj, users, type): users = as...
python
{ "resource": "" }
q30619
WinSCPBatch.add_uploads
train
def add_uploads(self, filemap): """Add the dict of uploads Parameters ----------
python
{ "resource": "" }
q30620
return_on_initial_capital
train
def return_on_initial_capital(capital, period_pl, leverage=None): """Return the daily return series based on the capital""" if capital <= 0: raise ValueError('cost must be
python
{ "resource": "" }
q30621
_listWrapOn
train
def _listWrapOn(F, availWidth, canv, mergeSpace=1, obj=None, dims=None): '''return max width, required height for a list of flowables F''' doct = getattr(canv, '_doctemplate', None) cframe = getattr(doct, 'frame', None) if cframe: from reportlab.platypus.doctemplate import _addGeneratedContent, ...
python
{ "resource": "" }
q30622
Positions.plot_rets
train
def plot_rets(self, ls=1, ax=None): """Plot each of the position returns :param ls: True, if positions should be broken into long/short :param ax: Axes :param regr: True, if regression line is shown """ import matplotlib.pyplot as plt from tia.util.mplot import A...
python
{ "resource": "" }
q30623
Positions.plot_ret_range
train
def plot_ret_range(self, ax=None, ls=0, dur=0): """Plot the return range for each position :param ax: Axes """ import matplotlib.pyplot as plt from tia.util.mplot import AxesFormat if ax is None: ax = plt.gca() frame = self.frame pids = fram...
python
{ "resource": "" }
q30624
PositionsStats.consecutive_frame
train
def consecutive_frame(self): """Return a DataFrame with columns cnt, pids, pl. cnt is the number of pids in the sequence. pl is the pl sum""" if self._frame.empty: return pd.DataFrame(columns=['pids', 'pl', 'cnt', 'is_win']) else: vals = (self._frame[PC.RET] >= 0).astype(...
python
{ "resource": "" }
q30625
ProfitAndLossDetails.asfreq
train
def asfreq(self, freq): """Resample the p&l at the specified frequency :param freq: :return: Pl object """ frame = self.frame if freq == 'B': resampled = frame.groupby(frame.index.date).apply(lambda
python
{ "resource": "" }
q30626
GridHelper.get_axes
train
def get_axes(self, idx): """ Allow for simple indexing """ cidx = 0 if idx > 0: cidx = idx % self.ncols
python
{ "resource": "" }
q30627
periodicity
train
def periodicity(freq_or_frame): """ resolve the number of periods per year """ if hasattr(freq_or_frame, 'rule_code'): rc = freq_or_frame.rule_code rc = rc.split('-')[0] factor = PER_YEAR_MAP.get(rc, None) if factor is not None: return factor / abs(freq_or_fra...
python
{ "resource": "" }
q30628
_resolve_periods_in_year
train
def _resolve_periods_in_year(scale, frame): """ Convert the scale to an annualzation factor. If scale is None then attempt to resolve from frame. If scale is a scalar then use it. If scale is a string then use it to lookup the annual factor """ if scale is None: return periodicity(frame) ...
python
{ "resource": "" }
q30629
returns_cumulative
train
def returns_cumulative(returns, geometric=True, expanding=False): """ return the cumulative return Parameters ---------- returns : DataFrame or Series geometric : bool, default is True If True, geometrically link returns expanding : bool default is False If True,...
python
{ "resource": "" }
q30630
rolling_returns_cumulative
train
def rolling_returns_cumulative(returns, window, min_periods=1, geometric=True): """ return the rolling cumulative returns Parameters ---------- returns : DataFrame or Series window : number of observations min_periods : minimum number of observations in a window geometric : link the returns...
python
{ "resource": "" }
q30631
returns_annualized
train
def returns_annualized(returns, geometric=True, scale=None, expanding=False): """ return the annualized cumulative returns Parameters ---------- returns : DataFrame or Series geometric : link the returns geometrically scale: None or scalar or string (ie 12 for months in year), If Non...
python
{ "resource": "" }
q30632
information_ratio
train
def information_ratio(rets, bm_rets, scale=None, expanding=False): """Information ratio, a common measure of manager efficiency, evaluates excess returns over a benchmark versus tracking error. :param rets: period returns :param bm_rets: periodic benchmark returns (not annualized) :param scale: Non...
python
{ "resource": "" }
q30633
rolling_percentileofscore
train
def rolling_percentileofscore(series, window, min_periods=None): """Computue the score percentile for the specified window.""" import scipy.stats as stats def _percentile(arr): score = arr[-1] vals = arr[:-1] return stats.percentileofscore(vals, score) notnull = series.dropna()...
python
{ "resource": "" }
q30634
PdfBuilder.new_title_bar
train
def new_title_bar(self, title, color=None): """Return an array of Pdf Objects which constitute a Header""" # Build a title bar for top of page w, t, c = '100%', 2, color or HexColor('#404040') title = '<b>{0}</b>'.format(title) if 'TitleBar' not in self.stylesheet: tb...
python
{ "resource": "" }
q30635
PdfBuilder.build_page
train
def build_page(self, template_id, flowable_map): """Build a pdf page by looking up the specified template and then mapping the flowable_map items to the appropriate named Frame """ pt = self.get_page_template(template_id) # If this is the first page then ensure the page template ...
python
{ "resource": "" }
q30636
PdfBuilder.table_formatter
train
def table_formatter(self, dataframe, inc_header=1, inc_index=1): """Return a table formatter for the dataframe. Saves the user the need to import this class"""
python
{ "resource": "" }
q30637
PortfolioPricer.get_mkt_val
train
def get_mkt_val(self, pxs=None): """ return the market value series for the specified
python
{ "resource": "" }
q30638
InstrumentPrices.volatility
train
def volatility(self, n, freq=None, which='close', ann=True, model='ln', min_periods=1, rolling='simple'): """Return the annualized volatility series. N is the number of lookback periods. :param n: int, number of lookback periods :param freq: resample frequency or None :param which: pric...
python
{ "resource": "" }
q30639
Instrument.get_mkt_val
train
def get_mkt_val(self, pxs=None): """Return the market value series for the series of pxs""" pxs = pxs if pxs is
python
{ "resource": "" }
q30640
Instrument.get_eod_frame
train
def get_eod_frame(self): """Return the eod market data frame for pricing""" close = self.pxs.close mktval = self.get_mkt_val(close) dvds = self.pxs.dvds
python
{ "resource": "" }
q30641
Instrument.truncate
train
def truncate(self, before=None, after=None): """Return an instrument with prices starting at before and ending at after""" pxframe = self.pxs.frame if (before is None or before == pxframe.index[0]) and (after is None or after == pxframe.index[-1]): return self else:
python
{ "resource": "" }
q30642
insert_level
train
def insert_level(df, label, level=0, copy=0, axis=0, level_name=None): """Add a new level to the index with the specified label. The newly created index will be a MultiIndex. :param df: DataFrame :param label: label to insert :param copy: If True, copy the DataFrame before assigning new index ...
python
{ "resource": "" }
q30643
APO
train
def APO(series, fast=12, slow=26, matype=0): """double exponential
python
{ "resource": "" }
q30644
MAMA
train
def MAMA(series, fast=.5, slow=.05): """MESA Adaptive Moving Average"""
python
{ "resource": "" }
q30645
MFI
train
def MFI(frame, n=14, high_col='high', low_col='low', close_col='close', vol_col='Volume'): """money flow inedx"""
python
{ "resource": "" }
q30646
Trade.split
train
def split(self, amt): """ return 2 trades, 1 with specific amt and the other with self.quantity - amt """ ratio = abs(amt / self.qty) t1 = Trade(self.tid, self.ts, amt, self.px, fees=ratio * self.fees, **self.kwargs)
python
{ "resource": "" }
q30647
pad_positive_wrapper
train
def pad_positive_wrapper(fmtfct): """Ensure that numbers are aligned in table by appending a blank space to postive values if 'parenthesis' are used to denote negative numbers"""
python
{ "resource": "" }
q30648
RegionFormatter.iter_rows
train
def iter_rows(self, start=None, end=None): """Iterate each of the Region rows in this region""" start = start or 0
python
{ "resource": "" }
q30649
RegionFormatter.iter_cols
train
def iter_cols(self, start=None, end=None): """Iterate each of the Region cols in this region""" start = start or 0
python
{ "resource": "" }
q30650
RegionFormatter.guess_number_format
train
def guess_number_format(self, rb=1, align=1, **fmt_args): """Determine the most appropriate formatter by inspected
python
{ "resource": "" }
q30651
RegionFormatter.dynamic_number_format
train
def dynamic_number_format(self, rb=1, align=1, **fmt_args): """Formatter changes based on the cell value"""
python
{ "resource": "" }
q30652
ShortTermReport.add_summary_page
train
def add_summary_page(self): """Build a table which is shown on the first page which gives an overview of the portfolios""" s = PortfolioSummary() s.include_long_short() pieces = [] for r in self.results: tmp = s(r.port, PortfolioSummary.analyze_returns) tm...
python
{ "resource": "" }
q30653
Request.set_flag
train
def set_flag(self, request, val, fld): """If the specified val is not None, then set the specified field to its boolean value""" if val is
python
{ "resource": "" }
q30654
XmlHelper.as_security_error
train
def as_security_error(node, secid): """ convert the securityError element to a SecurityError """ assert node.Name == 'securityError' src = XmlHelper.get_child_value(node, 'source') code = XmlHelper.get_child_value(node, 'code')
python
{ "resource": "" }
q30655
ResponseHandler.do_init
train
def do_init(self, handler): """ will be called prior to waiting for the message """ self.waiting = True
python
{ "resource": "" }
q30656
ReferenceDataRequest.response_as_series
train
def response_as_series(self): """ Return the response as a single series """ assert len(self.symbols) == 1, 'expected single request' if self.response_type == 'frame':
python
{ "resource": "" }
q30657
HistoricalDataRequest.response_as_single
train
def response_as_single(self, copy=0): """ convert the response map to a single data frame with Multi-Index columns """ arr = [] for sid, frame in self.response.iteritems(): if copy: frame = frame.copy()
python
{ "resource": "" }
q30658
LSML_Supervised.fit
train
def fit(self, X, y, random_state=np.random): """Create constraints from labels and learn the LSML model. Parameters ---------- X : (n x d) matrix Input data, where each row corresponds to a single instance. y : (n) array-like Data labels. random_state : numpy.random.RandomStat...
python
{ "resource": "" }
q30659
MLKR.fit
train
def fit(self, X, y): """ Fit MLKR model Parameters ---------- X : (n x d) array of samples y : (n) data labels """ X, y = self._prepare_inputs(X, y, y_numeric=True, ensure_min_samples=2) n, d = X.shape if y.shape[0] != n: ...
python
{ "resource": "" }
q30660
Constraints.chunks
train
def chunks(self, num_chunks=100, chunk_size=2, random_state=np.random): """ the random state object to be passed must be a numpy random seed """ chunks = -np.ones_like(self.known_label_idx, dtype=int) uniq, lookup = np.unique(self.known_labels, return_inverse=True) all_inds = [set(np.where(looku...
python
{ "resource": "" }
q30661
_BaseMMC._fD
train
def _fD(self, neg_pairs, A): """The value of the dissimilarity constraint function. f = f(\sum_{ij \in D} distance(x_i, x_j)) i.e. distance can be L1: \sqrt{(x_i-x_j)A(x_i-x_j)'} """
python
{ "resource": "" }
q30662
_BaseMMC._fD1
train
def _fD1(self, neg_pairs, A): """The gradient of the dissimilarity constraint function w.r.t. A. For example, let distance by L1 norm: f = f(\sum_{ij \in D} \sqrt{(x_i-x_j)A(x_i-x_j)'}) df/dA_{kl} = f'* d(\sum_{ij \in D} \sqrt{(x_i-x_j)^k*(x_i-x_j)^l})/dA_{kl} Note that d_ij*A*d_ij' = tr(d_ij*A*d_...
python
{ "resource": "" }
q30663
_BaseMMC._fS1
train
def _fS1(self, pos_pairs, A): """The gradient of the similarity constraint function w.r.t. A. f = \sum_{ij}(x_i-x_j)A(x_i-x_j)' = \sum_{ij}d_ij*A*d_ij' df/dA = d(d_ij*A*d_ij')/dA Note that d_ij*A*d_ij' = tr(d_ij*A*d_ij') = tr(d_ij'*d_ij*A) so,
python
{ "resource": "" }
q30664
MMC.fit
train
def fit(self, pairs, y, calibration_params=None): """Learn the MMC model. The threshold will be calibrated on the trainset using the parameters `calibration_params`. Parameters ---------- pairs : array-like, shape=(n_constraints, 2, n_features) or (n_constraints, 2) 3D Array...
python
{ "resource": "" }
q30665
MMC_Supervised.fit
train
def fit(self, X, y, random_state=np.random): """Create constraints from labels and learn the MMC model. Parameters ---------- X : (n x d) matrix Input data, where each row corresponds to a single instance. y : (n) array-like Data labels. random_state : numpy.random.RandomState, ...
python
{ "resource": "" }
q30666
LFDA.fit
train
def fit(self, X, y): '''Fit the LFDA model. Parameters ---------- X : (n, d) array-like Input data. y : (n,) array-like Class labels, one per point of data. ''' X, y = self._prepare_inputs(X, y, ensure_min_samples=2) unique_classes, y = np.unique(y, return_inverse=True)...
python
{ "resource": "" }
q30667
BaseMetricLearner._prepare_inputs
train
def _prepare_inputs(self, X, y=None, type_of_inputs='classic', **kwargs): """Initializes the preprocessor and processes inputs. See `check_input` for more details. Parameters ---------- input: array-like The input data array to check. y : array-like The input ...
python
{ "resource": "" }
q30668
MahalanobisMixin.score_pairs
train
def score_pairs(self, pairs): """Returns the learned Mahalanobis distance between pairs. This distance is defined as: :math:`d_M(x, x') = \sqrt{(x-x')^T M (x-x')}` where ``M`` is the learned Mahalanobis matrix, for every pair of points ``x`` and ``x'``. This corresponds to the euclidean distance betwee...
python
{ "resource": "" }
q30669
MahalanobisMixin.transform
train
def transform(self, X): """Embeds data points in the learned linear embedding space. Transforms samples in ``X`` into ``X_embedded``, samples inside a new embedding space such that: ``X_embedded = X.dot(L.T)``, where ``L`` is the learned linear transformation (See :class:`MahalanobisMixin`). Param...
python
{ "resource": "" }
q30670
_PairsClassifierMixin.decision_function
train
def decision_function(self, pairs): """Returns the decision function used to classify the pairs. Returns the opposite of the learned metric value between samples in every pair, to be consistent with scikit-learn conventions. Hence it should ideally be low for dissimilar samples and high for similar sam...
python
{ "resource": "" }
q30671
_PairsClassifierMixin.calibrate_threshold
train
def calibrate_threshold(self, pairs_valid, y_valid, strategy='accuracy', min_rate=None, beta=1.): """Decision threshold calibration for pairwise binary classification Method that calibrates the decision threshold (cutoff point) of the metric learner. This threshold will then be us...
python
{ "resource": "" }
q30672
_PairsClassifierMixin._validate_calibration_params
train
def _validate_calibration_params(strategy='accuracy', min_rate=None, beta=1.): """Ensure that calibration parameters have allowed values""" if strategy not in ('accuracy', 'f_beta', 'max_tpr', 'max_tnr'): raise ValueError('Strategy can either be "...
python
{ "resource": "" }
q30673
_QuadrupletsClassifierMixin.predict
train
def predict(self, quadruplets): """Predicts the ordering between sample distances in input quadruplets. For each quadruplet, returns 1 if the quadruplet is in the right order ( first pair is more similar than second pair), and -1 if not. Parameters ---------- quadruplets : array-like, shape=(n...
python
{ "resource": "" }
q30674
RCA.fit
train
def fit(self, X, chunks): """Learn the RCA model. Parameters ---------- data : (n x d) data matrix Each row corresponds to a single instance chunks : (n,) array of ints When ``chunks[i] == -1``, point i doesn't belong to any chunklet. When ``chunks[i] == j``, point i belongs...
python
{ "resource": "" }
q30675
RCA_Supervised.fit
train
def fit(self, X, y, random_state=np.random): """Create constraints from labels and learn the RCA model. Needs num_constraints specified in constructor. Parameters ---------- X : (n x d) data matrix each row corresponds to a single instance y : (n) data labels random_state : a random...
python
{ "resource": "" }
q30676
make_name
train
def make_name(estimator): """Helper function that returns the name of estimator or the given string if a string is given """ if estimator is not None: if isinstance(estimator, six.string_types): estimator_name =
python
{ "resource": "" }
q30677
UploadToDeprecatedPyPIDetected.from_args
train
def from_args(cls, target_url, default_url, test_url): """Return an UploadToDeprecatedPyPIDetected instance.""" return cls("You're trying to upload to the legacy PyPI site '{}'. " "Uploading to those sites is deprecated. \n " "The new sites are pypi.org and test.pyp...
python
{ "resource": "" }
q30678
check_status_code
train
def check_status_code(response, verbose): """ Shouldn't happen, thanks to the UploadToDeprecatedPyPIDetected exception, but this is in case that breaks and it does. """ if (response.status_code == 410 and response.url.startswith(("https://pypi.python.org", ...
python
{ "resource": "" }
q30679
no_positional
train
def no_positional(allow_self=False): """A decorator that doesn't allow for positional arguments. :param bool allow_self: Whether to allow ``self`` as a positional argument. """ def reject_positional_args(function): @functools.wraps(function) def wrapper(*args, **kwargs): ...
python
{ "resource": "" }
q30680
Wheel.find_candidate_metadata_files
train
def find_candidate_metadata_files(names): """Filter files that may be METADATA files.""" tuples = [
python
{ "resource": "" }
q30681
HashManager.hash
train
def hash(self): """Hash the file contents.""" with open(self.filename, "rb") as fp: for content in iter(lambda: fp.read(io.DEFAULT_BUFFER_SIZE), b''):
python
{ "resource": "" }
q30682
Settings.register_argparse_arguments
train
def register_argparse_arguments(parser): """Register the arguments for argparse.""" parser.add_argument( "-r", "--repository", action=utils.EnvironmentDefault, env="TWINE_REPOSITORY", default="pypi", help="The repository (package index) to uplo...
python
{ "resource": "" }
q30683
Settings.from_argparse
train
def from_argparse(cls, args): """Generate the Settings from parsed arguments.""" settings = vars(args)
python
{ "resource": "" }
q30684
Settings.check_repository_url
train
def check_repository_url(self): """Verify we are not using legacy PyPI. :raises: :class:`~twine.exceptions.UploadToDeprecatedPyPIDetected` """ repository_url = self.repository_config['repository']
python
{ "resource": "" }
q30685
Settings.create_repository
train
def create_repository(self): """Create a new repository for uploading.""" repo = repository.Repository( self.repository_config['repository'], self.username, self.password,
python
{ "resource": "" }
q30686
get_var_dict_from_ctx
train
def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = '_'): """ Returns the dict to be used in REPL for a given Context. """ raw_var_dict = { 'author': ctx.author, 'bot': ctx.bot, 'channel': ctx.channel, 'ctx': ctx, 'find':
python
{ "resource": "" }
q30687
background_reader
train
def background_reader(stream, loop: asyncio.AbstractEventLoop, callback): """ Reads a stream and forwards each line to an async callback. """ for line
python
{ "resource": "" }
q30688
ShellReader.make_reader_task
train
def make_reader_task(self, stream, callback): """ Create a reader executor task for a stream. """
python
{ "resource": "" }
q30689
ShellReader.clean_bytes
train
def clean_bytes(line): """ Cleans a byte sequence of shell directives and decodes it. """ text = line.decode('utf-8').replace('\r', '').strip('\n')
python
{ "resource": "" }
q30690
ShellReader.stderr_handler
train
async def stderr_handler(self, line): """ Handler for this class for stderr. """
python
{ "resource": "" }
q30691
wrap_code
train
def wrap_code(code: str, args: str = '') -> ast.Module: """ Compiles Python code into an async function or generator, and automatically adds return if the function body is a single evaluation. Also adds inline import expression support. """ if sys.version_info >= (3, 7): user_code = imp...
python
{ "resource": "" }
q30692
AsyncCodeExecutor.traverse
train
async def traverse(self, func): """ Traverses an async function or generator, yielding each result. This function is private. The class should be used as an iterator instead of using this method. """ # this allows the reference to be stolen
python
{ "resource": "" }
q30693
get_parent_scope_from_var
train
def get_parent_scope_from_var(name, global_ok=False, skip_frames=0) -> typing.Optional[Scope]: """ Iterates up the frame stack looking for a frame-scope containing the given variable name. Returns -------- Optional[Scope] The relevant :class:`Scope` or None """ stack = inspect.stac...
python
{ "resource": "" }
q30694
get_parent_var
train
def get_parent_var(name, global_ok=False, default=None, skip_frames=0): """ Directly gets a variable from a parent frame-scope. Returns -------- Any The content of the variable found by
python
{ "resource": "" }
q30695
Scope.clear_intersection
train
def clear_intersection(self, other_dict): """ Clears out locals and globals from this scope where the key-value pair matches with other_dict. This allows cleanup of temporary variables that may have washed up into this Scope. Arguments --------- other_di...
python
{ "resource": "" }
q30696
Scope.update
train
def update(self, other): """ Updates this scope with the content of another scope. Arguments --------- other: a :class:`Scope` instance. Returns ------- Scope
python
{ "resource": "" }
q30697
send_traceback
train
async def send_traceback(destination: discord.abc.Messageable, verbosity: int, *exc_info): """ Sends a traceback of an exception to a destination. Used when REPL fails for any reason. :param destination: Where to send this information to :param verbosity: How far back this traceback should go. 0 sh...
python
{ "resource": "" }
q30698
do_after_sleep
train
async def do_after_sleep(delay: float, coro, *args, **kwargs): """ Performs an action after a set amount of time. This function only calls the coroutine after the delay, preventing asyncio complaints about destroyed coros. :param delay: Time in seconds :param coro: Coroutine to run :param ...
python
{ "resource": "" }
q30699
attempt_add_reaction
train
async def attempt_add_reaction(msg: discord.Message, reaction: typing.Union[str, discord.Emoji])\ -> typing.Optional[discord.Reaction]: """ Try to add a reaction to a message, ignoring it if it fails for any reason. :param msg: The message to add the reaction to. :param reaction: The reaction e...
python
{ "resource": "" }