repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
quantopian/empyrical
empyrical/stats.py
up_capture
def up_capture(returns, factor_returns, **kwargs): """ Compute the capture ratio for periods when the benchmark return is positive Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_capture : float Note ---- See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for more information. """ return up(returns, factor_returns, function=capture, **kwargs)
python
def up_capture(returns, factor_returns, **kwargs): """ Compute the capture ratio for periods when the benchmark return is positive Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_capture : float Note ---- See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for more information. """ return up(returns, factor_returns, function=capture, **kwargs)
[ "def", "up_capture", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "up", "(", "returns", ",", "factor_returns", ",", "function", "=", "capture", ",", "*", "*", "kwargs", ")" ]
Compute the capture ratio for periods when the benchmark return is positive Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_capture : float Note ---- See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for more information.
[ "Compute", "the", "capture", "ratio", "for", "periods", "when", "the", "benchmark", "return", "is", "positive" ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1549-L1580
train
219,500
quantopian/empyrical
empyrical/stats.py
down_capture
def down_capture(returns, factor_returns, **kwargs): """ Compute the capture ratio for periods when the benchmark return is negative Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- down_capture : float Note ---- See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for more information. """ return down(returns, factor_returns, function=capture, **kwargs)
python
def down_capture(returns, factor_returns, **kwargs): """ Compute the capture ratio for periods when the benchmark return is negative Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- down_capture : float Note ---- See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for more information. """ return down(returns, factor_returns, function=capture, **kwargs)
[ "def", "down_capture", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "down", "(", "returns", ",", "factor_returns", ",", "function", "=", "capture", ",", "*", "*", "kwargs", ")" ]
Compute the capture ratio for periods when the benchmark return is negative Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- down_capture : float Note ---- See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for more information.
[ "Compute", "the", "capture", "ratio", "for", "periods", "when", "the", "benchmark", "return", "is", "negative" ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1583-L1614
train
219,501
quantopian/empyrical
empyrical/stats.py
up_down_capture
def up_down_capture(returns, factor_returns, **kwargs): """ Computes the ratio of up_capture to down_capture. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_down_capture : float the updown capture ratio """ return (up_capture(returns, factor_returns, **kwargs) / down_capture(returns, factor_returns, **kwargs))
python
def up_down_capture(returns, factor_returns, **kwargs): """ Computes the ratio of up_capture to down_capture. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_down_capture : float the updown capture ratio """ return (up_capture(returns, factor_returns, **kwargs) / down_capture(returns, factor_returns, **kwargs))
[ "def", "up_down_capture", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "(", "up_capture", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", "/", "down_capture", "(", "returns", ",", "factor_returns", ...
Computes the ratio of up_capture to down_capture. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series or np.ndarray Noncumulative returns of the factor to which beta is computed. Usually a benchmark such as the market. - This is in the same style as returns. period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: 'monthly':12 'weekly': 52 'daily': 252 Returns ------- up_down_capture : float the updown capture ratio
[ "Computes", "the", "ratio", "of", "up_capture", "to", "down_capture", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1617-L1645
train
219,502
quantopian/empyrical
empyrical/stats.py
up_alpha_beta
def up_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is positive. Parameters ---------- see documentation for `alpha_beta`. Returns ------- float Alpha. float Beta. """ return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs)
python
def up_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is positive. Parameters ---------- see documentation for `alpha_beta`. Returns ------- float Alpha. float Beta. """ return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs)
[ "def", "up_alpha_beta", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "up", "(", "returns", ",", "factor_returns", ",", "function", "=", "alpha_beta_aligned", ",", "*", "*", "kwargs", ")" ]
Computes alpha and beta for periods when the benchmark return is positive. Parameters ---------- see documentation for `alpha_beta`. Returns ------- float Alpha. float Beta.
[ "Computes", "alpha", "and", "beta", "for", "periods", "when", "the", "benchmark", "return", "is", "positive", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1648-L1663
train
219,503
quantopian/empyrical
empyrical/stats.py
down_alpha_beta
def down_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float """ return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs)
python
def down_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float """ return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs)
[ "def", "down_alpha_beta", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "down", "(", "returns", ",", "factor_returns", ",", "function", "=", "alpha_beta_aligned", ",", "*", "*", "kwargs", ")" ]
Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float
[ "Computes", "alpha", "and", "beta", "for", "periods", "when", "the", "benchmark", "return", "is", "negative", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1666-L1679
train
219,504
quantopian/empyrical
empyrical/utils.py
roll
def roll(*args, **kwargs): """ Calculates a given statistic across a rolling time period. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. window (keyword): int the number of periods included in each calculation. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- np.ndarray, pd.Series depends on input type ndarray(s) ==> ndarray Series(s) ==> pd.Series A Series or ndarray of the results of the stat across the rolling window. """ func = kwargs.pop('function') window = kwargs.pop('window') if len(args) > 2: raise ValueError("Cannot pass more than 2 return sets") if len(args) == 2: if not isinstance(args[0], type(args[1])): raise ValueError("The two returns arguments are not the same.") if isinstance(args[0], np.ndarray): return _roll_ndarray(func, window, *args, **kwargs) return _roll_pandas(func, window, *args, **kwargs)
python
def roll(*args, **kwargs): """ Calculates a given statistic across a rolling time period. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. window (keyword): int the number of periods included in each calculation. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- np.ndarray, pd.Series depends on input type ndarray(s) ==> ndarray Series(s) ==> pd.Series A Series or ndarray of the results of the stat across the rolling window. """ func = kwargs.pop('function') window = kwargs.pop('window') if len(args) > 2: raise ValueError("Cannot pass more than 2 return sets") if len(args) == 2: if not isinstance(args[0], type(args[1])): raise ValueError("The two returns arguments are not the same.") if isinstance(args[0], np.ndarray): return _roll_ndarray(func, window, *args, **kwargs) return _roll_pandas(func, window, *args, **kwargs)
[ "def", "roll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "=", "kwargs", ".", "pop", "(", "'function'", ")", "window", "=", "kwargs", ".", "pop", "(", "'window'", ")", "if", "len", "(", "args", ")", ">", "2", ":", "raise", "Va...
Calculates a given statistic across a rolling time period. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. window (keyword): int the number of periods included in each calculation. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- np.ndarray, pd.Series depends on input type ndarray(s) ==> ndarray Series(s) ==> pd.Series A Series or ndarray of the results of the stat across the rolling window.
[ "Calculates", "a", "given", "statistic", "across", "a", "rolling", "time", "period", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L78-L118
train
219,505
quantopian/empyrical
empyrical/utils.py
up
def up(returns, factor_returns, **kwargs): """ Calculates a given statistic filtering only positive factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the function """ func = kwargs.pop('function') returns = returns[factor_returns > 0] factor_returns = factor_returns[factor_returns > 0] return func(returns, factor_returns, **kwargs)
python
def up(returns, factor_returns, **kwargs): """ Calculates a given statistic filtering only positive factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the function """ func = kwargs.pop('function') returns = returns[factor_returns > 0] factor_returns = factor_returns[factor_returns > 0] return func(returns, factor_returns, **kwargs)
[ "def", "up", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "func", "=", "kwargs", ".", "pop", "(", "'function'", ")", "returns", "=", "returns", "[", "factor_returns", ">", "0", "]", "factor_returns", "=", "factor_returns", "[...
Calculates a given statistic filtering only positive factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the function
[ "Calculates", "a", "given", "statistic", "filtering", "only", "positive", "factor", "return", "periods", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L121-L144
train
219,506
quantopian/empyrical
empyrical/utils.py
down
def down(returns, factor_returns, **kwargs): """ Calculates a given statistic filtering only negative factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the 'function' """ func = kwargs.pop('function') returns = returns[factor_returns < 0] factor_returns = factor_returns[factor_returns < 0] return func(returns, factor_returns, **kwargs)
python
def down(returns, factor_returns, **kwargs): """ Calculates a given statistic filtering only negative factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the 'function' """ func = kwargs.pop('function') returns = returns[factor_returns < 0] factor_returns = factor_returns[factor_returns < 0] return func(returns, factor_returns, **kwargs)
[ "def", "down", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "func", "=", "kwargs", ".", "pop", "(", "'function'", ")", "returns", "=", "returns", "[", "factor_returns", "<", "0", "]", "factor_returns", "=", "factor_returns", ...
Calculates a given statistic filtering only negative factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns (optional): float / series Benchmark return to compare returns against. function: the function to run for each rolling window. (other keywords): other keywords that are required to be passed to the function in the 'function' argument may also be passed in. Returns ------- Same as the return of the 'function'
[ "Calculates", "a", "given", "statistic", "filtering", "only", "negative", "factor", "return", "periods", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L147-L170
train
219,507
quantopian/empyrical
empyrical/utils.py
get_treasury_yield
def get_treasury_yield(start=None, end=None, period='3MO'): """ Load treasury yields from FRED. Parameters ---------- start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional Which maturity to use. Returns ------- pd.Series Annual treasury yield for every day. """ if start is None: start = '1/1/1970' if end is None: end = _1_bday_ago() treasury = web.DataReader("DGS3{}".format(period), "fred", start, end) treasury = treasury.ffill() return treasury
python
def get_treasury_yield(start=None, end=None, period='3MO'): """ Load treasury yields from FRED. Parameters ---------- start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional Which maturity to use. Returns ------- pd.Series Annual treasury yield for every day. """ if start is None: start = '1/1/1970' if end is None: end = _1_bday_ago() treasury = web.DataReader("DGS3{}".format(period), "fred", start, end) treasury = treasury.ffill() return treasury
[ "def", "get_treasury_yield", "(", "start", "=", "None", ",", "end", "=", "None", ",", "period", "=", "'3MO'", ")", ":", "if", "start", "is", "None", ":", "start", "=", "'1/1/1970'", "if", "end", "is", "None", ":", "end", "=", "_1_bday_ago", "(", ")",...
Load treasury yields from FRED. Parameters ---------- start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional Which maturity to use. Returns ------- pd.Series Annual treasury yield for every day.
[ "Load", "treasury", "yields", "from", "FRED", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L379-L409
train
219,508
quantopian/empyrical
empyrical/utils.py
default_returns_func
def default_returns_func(symbol, start=None, end=None): """ Gets returns for a symbol. Queries Yahoo Finance. Attempts to cache SPY. Parameters ---------- symbol : str Ticker symbol, e.g. APPL. start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. Returns ------- pd.Series Daily returns for the symbol. - See full explanation in tears.create_full_tear_sheet (returns). """ if start is None: start = '1/1/1970' if end is None: end = _1_bday_ago() start = get_utc_timestamp(start) end = get_utc_timestamp(end) if symbol == 'SPY': filepath = data_path('spy.csv') rets = get_returns_cached(filepath, get_symbol_returns_from_yahoo, end, symbol='SPY', start='1/1/1970', end=datetime.now()) rets = rets[start:end] else: rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end) return rets[symbol]
python
def default_returns_func(symbol, start=None, end=None): """ Gets returns for a symbol. Queries Yahoo Finance. Attempts to cache SPY. Parameters ---------- symbol : str Ticker symbol, e.g. APPL. start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. Returns ------- pd.Series Daily returns for the symbol. - See full explanation in tears.create_full_tear_sheet (returns). """ if start is None: start = '1/1/1970' if end is None: end = _1_bday_ago() start = get_utc_timestamp(start) end = get_utc_timestamp(end) if symbol == 'SPY': filepath = data_path('spy.csv') rets = get_returns_cached(filepath, get_symbol_returns_from_yahoo, end, symbol='SPY', start='1/1/1970', end=datetime.now()) rets = rets[start:end] else: rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end) return rets[symbol]
[ "def", "default_returns_func", "(", "symbol", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "'1/1/1970'", "if", "end", "is", "None", ":", "end", "=", "_1_bday_ago", "(", ")", "start", "=...
Gets returns for a symbol. Queries Yahoo Finance. Attempts to cache SPY. Parameters ---------- symbol : str Ticker symbol, e.g. APPL. start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. Returns ------- pd.Series Daily returns for the symbol. - See full explanation in tears.create_full_tear_sheet (returns).
[ "Gets", "returns", "for", "a", "symbol", ".", "Queries", "Yahoo", "Finance", ".", "Attempts", "to", "cache", "SPY", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L452-L495
train
219,509
quantopian/empyrical
empyrical/perf_attrib.py
perf_attrib
def perf_attrib(returns, positions, factor_returns, factor_loadings): """ Attributes the performance of a returns stream to a set of risk factors. Performance attribution determines how much each risk factor, e.g., momentum, the technology sector, etc., contributed to total returns, as well as the daily exposure to each of the risk factors. The returns that can be attributed to one of the given risk factors are the `common_returns`, and the returns that _cannot_ be attributed to a risk factor are the `specific_returns`. The `common_returns` and `specific_returns` summed together will always equal the total returns. Parameters ---------- returns : pd.Series Returns for each day in the date range. - Example: 2017-01-01 -0.017098 2017-01-02 0.002683 2017-01-03 -0.008669 positions: pd.Series Daily holdings in percentages, indexed by date. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_returns : pd.DataFrame Returns by factor, with date as index and factors as columns - Example: momentum reversal 2017-01-01 0.002779 -0.005453 2017-01-02 0.001096 0.010290 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- tuple of (risk_exposures_portfolio, perf_attribution) risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 perf_attribution : pd.DataFrame df with factors, common returns, and specific returns as columns, and datetimes as index - Example: momentum reversal common_returns specific_returns dt 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980 Note ---- See https://en.wikipedia.org/wiki/Performance_attribution for more details. """ risk_exposures_portfolio = compute_exposures(positions, factor_loadings) perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns) common_returns = perf_attrib_by_factor.sum(axis='columns') specific_returns = returns - common_returns returns_df = pd.DataFrame({'total_returns': returns, 'common_returns': common_returns, 'specific_returns': specific_returns}) return (risk_exposures_portfolio, pd.concat([perf_attrib_by_factor, returns_df], axis='columns'))
python
def perf_attrib(returns, positions, factor_returns, factor_loadings): """ Attributes the performance of a returns stream to a set of risk factors. Performance attribution determines how much each risk factor, e.g., momentum, the technology sector, etc., contributed to total returns, as well as the daily exposure to each of the risk factors. The returns that can be attributed to one of the given risk factors are the `common_returns`, and the returns that _cannot_ be attributed to a risk factor are the `specific_returns`. The `common_returns` and `specific_returns` summed together will always equal the total returns. Parameters ---------- returns : pd.Series Returns for each day in the date range. - Example: 2017-01-01 -0.017098 2017-01-02 0.002683 2017-01-03 -0.008669 positions: pd.Series Daily holdings in percentages, indexed by date. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_returns : pd.DataFrame Returns by factor, with date as index and factors as columns - Example: momentum reversal 2017-01-01 0.002779 -0.005453 2017-01-02 0.001096 0.010290 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- tuple of (risk_exposures_portfolio, perf_attribution) risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 perf_attribution : pd.DataFrame df with factors, common returns, and specific returns as columns, and datetimes as index - Example: momentum reversal common_returns specific_returns dt 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980 Note ---- See https://en.wikipedia.org/wiki/Performance_attribution for more details. """ risk_exposures_portfolio = compute_exposures(positions, factor_loadings) perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns) common_returns = perf_attrib_by_factor.sum(axis='columns') specific_returns = returns - common_returns returns_df = pd.DataFrame({'total_returns': returns, 'common_returns': common_returns, 'specific_returns': specific_returns}) return (risk_exposures_portfolio, pd.concat([perf_attrib_by_factor, returns_df], axis='columns'))
[ "def", "perf_attrib", "(", "returns", ",", "positions", ",", "factor_returns", ",", "factor_loadings", ")", ":", "risk_exposures_portfolio", "=", "compute_exposures", "(", "positions", ",", "factor_loadings", ")", "perf_attrib_by_factor", "=", "risk_exposures_portfolio", ...
Attributes the performance of a returns stream to a set of risk factors. Performance attribution determines how much each risk factor, e.g., momentum, the technology sector, etc., contributed to total returns, as well as the daily exposure to each of the risk factors. The returns that can be attributed to one of the given risk factors are the `common_returns`, and the returns that _cannot_ be attributed to a risk factor are the `specific_returns`. The `common_returns` and `specific_returns` summed together will always equal the total returns. Parameters ---------- returns : pd.Series Returns for each day in the date range. - Example: 2017-01-01 -0.017098 2017-01-02 0.002683 2017-01-03 -0.008669 positions: pd.Series Daily holdings in percentages, indexed by date. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_returns : pd.DataFrame Returns by factor, with date as index and factors as columns - Example: momentum reversal 2017-01-01 0.002779 -0.005453 2017-01-02 0.001096 0.010290 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- tuple of (risk_exposures_portfolio, perf_attribution) risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 perf_attribution : pd.DataFrame df with factors, common returns, and specific returns as columns, and datetimes as index - Example: momentum reversal common_returns specific_returns dt 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980 Note ---- See https://en.wikipedia.org/wiki/Performance_attribution for more details.
[ "Attributes", "the", "performance", "of", "a", "returns", "stream", "to", "a", "set", "of", "risk", "factors", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L4-L97
train
219,510
quantopian/empyrical
empyrical/perf_attrib.py
compute_exposures
def compute_exposures(positions, factor_loadings): """ Compute daily risk factor exposures. Parameters ---------- positions: pd.Series A series of holdings as percentages indexed by date and ticker. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 """ risk_exposures = factor_loadings.multiply(positions, axis='rows') return risk_exposures.groupby(level='dt').sum()
python
def compute_exposures(positions, factor_loadings): """ Compute daily risk factor exposures. Parameters ---------- positions: pd.Series A series of holdings as percentages indexed by date and ticker. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 """ risk_exposures = factor_loadings.multiply(positions, axis='rows') return risk_exposures.groupby(level='dt').sum()
[ "def", "compute_exposures", "(", "positions", ",", "factor_loadings", ")", ":", "risk_exposures", "=", "factor_loadings", ".", "multiply", "(", "positions", ",", "axis", "=", "'rows'", ")", "return", "risk_exposures", ".", "groupby", "(", "level", "=", "'dt'", ...
Compute daily risk factor exposures. Parameters ---------- positions: pd.Series A series of holdings as percentages indexed by date and ticker. - Examples: dt ticker 2017-01-01 AAPL 0.417582 TLT 0.010989 XOM 0.571429 2017-01-02 AAPL 0.202381 TLT 0.535714 XOM 0.261905 factor_loadings : pd.DataFrame Factor loadings for all days in the date range, with date and ticker as index, and factors as columns. - Example: momentum reversal dt ticker 2017-01-01 AAPL -1.592914 0.852830 TLT 0.184864 0.895534 XOM 0.993160 1.149353 2017-01-02 AAPL -0.140009 -0.524952 TLT -1.066978 0.185435 XOM -1.798401 0.761549 Returns ------- risk_exposures_portfolio : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515
[ "Compute", "daily", "risk", "factor", "exposures", "." ]
badbdca75f5b293f28b5e947974894de041d6868
https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L100-L141
train
219,511
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling.has_pending
def has_pending(self): """Return True if there are pending test items. This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active". """ if self.workqueue: return True for assigned_unit in self.assigned_work.values(): if self._pending_of(assigned_unit) > 0: return True return False
python
def has_pending(self): """Return True if there are pending test items. This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active". """ if self.workqueue: return True for assigned_unit in self.assigned_work.values(): if self._pending_of(assigned_unit) > 0: return True return False
[ "def", "has_pending", "(", "self", ")", ":", "if", "self", ".", "workqueue", ":", "return", "True", "for", "assigned_unit", "in", "self", ".", "assigned_work", ".", "values", "(", ")", ":", "if", "self", ".", "_pending_of", "(", "assigned_unit", ")", ">"...
Return True if there are pending test items. This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active".
[ "Return", "True", "if", "there", "are", "pending", "test", "items", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L133-L147
train
219,512
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling.add_node
def add_node(self, node): """Add a new node to the scheduler. From now on the node will be assigned work units to be executed. Called by the ``DSession.worker_workerready`` hook when it successfully bootstraps a new node. """ assert node not in self.assigned_work self.assigned_work[node] = OrderedDict()
python
def add_node(self, node): """Add a new node to the scheduler. From now on the node will be assigned work units to be executed. Called by the ``DSession.worker_workerready`` hook when it successfully bootstraps a new node. """ assert node not in self.assigned_work self.assigned_work[node] = OrderedDict()
[ "def", "add_node", "(", "self", ",", "node", ")", ":", "assert", "node", "not", "in", "self", ".", "assigned_work", "self", ".", "assigned_work", "[", "node", "]", "=", "OrderedDict", "(", ")" ]
Add a new node to the scheduler. From now on the node will be assigned work units to be executed. Called by the ``DSession.worker_workerready`` hook when it successfully bootstraps a new node.
[ "Add", "a", "new", "node", "to", "the", "scheduler", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L149-L158
train
219,513
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling.remove_node
def remove_node(self, node): """Remove a node from the scheduler. This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the hooks: - ``DSession.worker_workerfinished``. - ``DSession.worker_errordown``. Return the item being executed while the node crashed or None if the node has no more pending items. """ workload = self.assigned_work.pop(node) if not self._pending_of(workload): return None # The node crashed, identify test that crashed for work_unit in workload.values(): for nodeid, completed in work_unit.items(): if not completed: crashitem = nodeid break else: continue break else: raise RuntimeError( "Unable to identify crashitem on a workload with pending items" ) # Made uncompleted work unit available again self.workqueue.update(workload) for node in self.assigned_work: self._reschedule(node) return crashitem
python
def remove_node(self, node): """Remove a node from the scheduler. This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the hooks: - ``DSession.worker_workerfinished``. - ``DSession.worker_errordown``. Return the item being executed while the node crashed or None if the node has no more pending items. """ workload = self.assigned_work.pop(node) if not self._pending_of(workload): return None # The node crashed, identify test that crashed for work_unit in workload.values(): for nodeid, completed in work_unit.items(): if not completed: crashitem = nodeid break else: continue break else: raise RuntimeError( "Unable to identify crashitem on a workload with pending items" ) # Made uncompleted work unit available again self.workqueue.update(workload) for node in self.assigned_work: self._reschedule(node) return crashitem
[ "def", "remove_node", "(", "self", ",", "node", ")", ":", "workload", "=", "self", ".", "assigned_work", ".", "pop", "(", "node", ")", "if", "not", "self", ".", "_pending_of", "(", "workload", ")", ":", "return", "None", "# The node crashed, identify test th...
Remove a node from the scheduler. This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the hooks: - ``DSession.worker_workerfinished``. - ``DSession.worker_errordown``. Return the item being executed while the node crashed or None if the node has no more pending items.
[ "Remove", "a", "node", "from", "the", "scheduler", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L160-L199
train
219,514
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling.add_node_collection
def add_node_collection(self, node, collection): """Add the collected test items from a node. The collection is stored in the ``.registered_collections`` dictionary. Called by the hook: - ``DSession.worker_collectionfinish``. """ # Check that add_node() was called on the node before assert node in self.assigned_work # A new node has been added later, perhaps an original one died. if self.collection_is_completed: # Assert that .schedule() should have been called by now assert self.collection # Check that the new collection matches the official collection if collection != self.collection: other_node = next(iter(self.registered_collections.keys())) msg = report_collection_diff( self.collection, collection, other_node.gateway.id, node.gateway.id ) self.log(msg) return self.registered_collections[node] = list(collection)
python
def add_node_collection(self, node, collection): """Add the collected test items from a node. The collection is stored in the ``.registered_collections`` dictionary. Called by the hook: - ``DSession.worker_collectionfinish``. """ # Check that add_node() was called on the node before assert node in self.assigned_work # A new node has been added later, perhaps an original one died. if self.collection_is_completed: # Assert that .schedule() should have been called by now assert self.collection # Check that the new collection matches the official collection if collection != self.collection: other_node = next(iter(self.registered_collections.keys())) msg = report_collection_diff( self.collection, collection, other_node.gateway.id, node.gateway.id ) self.log(msg) return self.registered_collections[node] = list(collection)
[ "def", "add_node_collection", "(", "self", ",", "node", ",", "collection", ")", ":", "# Check that add_node() was called on the node before", "assert", "node", "in", "self", ".", "assigned_work", "# A new node has been added later, perhaps an original one died.", "if", "self", ...
Add the collected test items from a node. The collection is stored in the ``.registered_collections`` dictionary. Called by the hook: - ``DSession.worker_collectionfinish``.
[ "Add", "the", "collected", "test", "items", "from", "a", "node", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L201-L231
train
219,515
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling._assign_work_unit
def _assign_work_unit(self, node): """Assign a work unit to a node.""" assert self.workqueue # Grab a unit of work scope, work_unit = self.workqueue.popitem(last=False) # Keep track of the assigned work assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict()) assigned_to_node[scope] = work_unit # Ask the node to execute the workload worker_collection = self.registered_collections[node] nodeids_indexes = [ worker_collection.index(nodeid) for nodeid, completed in work_unit.items() if not completed ] node.send_runtest_some(nodeids_indexes)
python
def _assign_work_unit(self, node): """Assign a work unit to a node.""" assert self.workqueue # Grab a unit of work scope, work_unit = self.workqueue.popitem(last=False) # Keep track of the assigned work assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict()) assigned_to_node[scope] = work_unit # Ask the node to execute the workload worker_collection = self.registered_collections[node] nodeids_indexes = [ worker_collection.index(nodeid) for nodeid, completed in work_unit.items() if not completed ] node.send_runtest_some(nodeids_indexes)
[ "def", "_assign_work_unit", "(", "self", ",", "node", ")", ":", "assert", "self", ".", "workqueue", "# Grab a unit of work", "scope", ",", "work_unit", "=", "self", ".", "workqueue", ".", "popitem", "(", "last", "=", "False", ")", "# Keep track of the assigned w...
Assign a work unit to a node.
[ "Assign", "a", "work", "unit", "to", "a", "node", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L246-L265
train
219,516
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling._pending_of
def _pending_of(self, workload): """Return the number of pending tests in a workload.""" pending = sum(list(scope.values()).count(False) for scope in workload.values()) return pending
python
def _pending_of(self, workload): """Return the number of pending tests in a workload.""" pending = sum(list(scope.values()).count(False) for scope in workload.values()) return pending
[ "def", "_pending_of", "(", "self", ",", "workload", ")", ":", "pending", "=", "sum", "(", "list", "(", "scope", ".", "values", "(", ")", ")", ".", "count", "(", "False", ")", "for", "scope", "in", "workload", ".", "values", "(", ")", ")", "return",...
Return the number of pending tests in a workload.
[ "Return", "the", "number", "of", "pending", "tests", "in", "a", "workload", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L291-L294
train
219,517
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling._reschedule
def _reschedule(self, node): """Maybe schedule new items on the node. If there are any globally pending work units left then this will check if the given node should be given any more tests. """ # Do not add more work to a node shutting down if node.shutting_down: return # Check that more work is available if not self.workqueue: node.shutdown() return self.log("Number of units waiting for node:", len(self.workqueue)) # Check that the node is almost depleted of work # 2: Heuristic of minimum tests to enqueue more work if self._pending_of(self.assigned_work[node]) > 2: return # Pop one unit of work and assign it self._assign_work_unit(node)
python
def _reschedule(self, node): """Maybe schedule new items on the node. If there are any globally pending work units left then this will check if the given node should be given any more tests. """ # Do not add more work to a node shutting down if node.shutting_down: return # Check that more work is available if not self.workqueue: node.shutdown() return self.log("Number of units waiting for node:", len(self.workqueue)) # Check that the node is almost depleted of work # 2: Heuristic of minimum tests to enqueue more work if self._pending_of(self.assigned_work[node]) > 2: return # Pop one unit of work and assign it self._assign_work_unit(node)
[ "def", "_reschedule", "(", "self", ",", "node", ")", ":", "# Do not add more work to a node shutting down", "if", "node", ".", "shutting_down", ":", "return", "# Check that more work is available", "if", "not", "self", ".", "workqueue", ":", "node", ".", "shutdown", ...
Maybe schedule new items on the node. If there are any globally pending work units left then this will check if the given node should be given any more tests.
[ "Maybe", "schedule", "new", "items", "on", "the", "node", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L296-L320
train
219,518
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
LoadScopeScheduling.schedule
def schedule(self): """Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collection_is_completed`` is True, this is called by the hook: - ``DSession.worker_collectionfinish``. """ assert self.collection_is_completed # Initial distribution already happened, reschedule on all nodes if self.collection is not None: for node in self.nodes: self._reschedule(node) return # Check that all nodes collected the same tests if not self._check_nodes_have_same_collection(): self.log("**Different tests collected, aborting run**") return # Collections are identical, create the final list of items self.collection = list(next(iter(self.registered_collections.values()))) if not self.collection: return # Determine chunks of work (scopes) for nodeid in self.collection: scope = self._split_scope(nodeid) work_unit = self.workqueue.setdefault(scope, default=OrderedDict()) work_unit[nodeid] = False # Avoid having more workers than work extra_nodes = len(self.nodes) - len(self.workqueue) if extra_nodes > 0: self.log("Shuting down {0} nodes".format(extra_nodes)) for _ in range(extra_nodes): unused_node, assigned = self.assigned_work.popitem(last=True) self.log("Shuting down unused node {0}".format(unused_node)) unused_node.shutdown() # Assign initial workload for node in self.nodes: self._assign_work_unit(node) # Ensure nodes start with at least two work units if possible (#277) for node in self.nodes: self._reschedule(node) # Initial distribution sent all tests, start node shutdown if not self.workqueue: for node in self.nodes: node.shutdown()
python
def schedule(self): """Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collection_is_completed`` is True, this is called by the hook: - ``DSession.worker_collectionfinish``. """ assert self.collection_is_completed # Initial distribution already happened, reschedule on all nodes if self.collection is not None: for node in self.nodes: self._reschedule(node) return # Check that all nodes collected the same tests if not self._check_nodes_have_same_collection(): self.log("**Different tests collected, aborting run**") return # Collections are identical, create the final list of items self.collection = list(next(iter(self.registered_collections.values()))) if not self.collection: return # Determine chunks of work (scopes) for nodeid in self.collection: scope = self._split_scope(nodeid) work_unit = self.workqueue.setdefault(scope, default=OrderedDict()) work_unit[nodeid] = False # Avoid having more workers than work extra_nodes = len(self.nodes) - len(self.workqueue) if extra_nodes > 0: self.log("Shuting down {0} nodes".format(extra_nodes)) for _ in range(extra_nodes): unused_node, assigned = self.assigned_work.popitem(last=True) self.log("Shuting down unused node {0}".format(unused_node)) unused_node.shutdown() # Assign initial workload for node in self.nodes: self._assign_work_unit(node) # Ensure nodes start with at least two work units if possible (#277) for node in self.nodes: self._reschedule(node) # Initial distribution sent all tests, start node shutdown if not self.workqueue: for node in self.nodes: node.shutdown()
[ "def", "schedule", "(", "self", ")", ":", "assert", "self", ".", "collection_is_completed", "# Initial distribution already happened, reschedule on all nodes", "if", "self", ".", "collection", "is", "not", "None", ":", "for", "node", "in", "self", ".", "nodes", ":",...
Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collection_is_completed`` is True, this is called by the hook: - ``DSession.worker_collectionfinish``.
[ "Initiate", "distribution", "of", "the", "test", "collection", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380
train
219,519
pytest-dev/pytest-xdist
xdist/scheduler/each.py
EachScheduling.schedule
def schedule(self): """Schedule the test items on the nodes If the node's pending list is empty it is a new node which needs to run all the tests. If the pending list is already populated (by ``.add_node_collection()``) then it replaces a dead node and we only need to run those tests. """ assert self.collection_is_completed for node, pending in self.node2pending.items(): if node in self._started: continue if not pending: pending[:] = range(len(self.node2collection[node])) node.send_runtest_all() node.shutdown() else: node.send_runtest_some(pending) self._started.append(node)
python
def schedule(self): """Schedule the test items on the nodes If the node's pending list is empty it is a new node which needs to run all the tests. If the pending list is already populated (by ``.add_node_collection()``) then it replaces a dead node and we only need to run those tests. """ assert self.collection_is_completed for node, pending in self.node2pending.items(): if node in self._started: continue if not pending: pending[:] = range(len(self.node2collection[node])) node.send_runtest_all() node.shutdown() else: node.send_runtest_some(pending) self._started.append(node)
[ "def", "schedule", "(", "self", ")", ":", "assert", "self", ".", "collection_is_completed", "for", "node", ",", "pending", "in", "self", ".", "node2pending", ".", "items", "(", ")", ":", "if", "node", "in", "self", ".", "_started", ":", "continue", "if",...
Schedule the test items on the nodes If the node's pending list is empty it is a new node which needs to run all the tests. If the pending list is already populated (by ``.add_node_collection()``) then it replaces a dead node and we only need to run those tests.
[ "Schedule", "the", "test", "items", "on", "the", "nodes" ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/each.py#L114-L132
train
219,520
pytest-dev/pytest-xdist
xdist/scheduler/load.py
LoadScheduling.has_pending
def has_pending(self): """Return True if there are pending test items This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active". """ if self.pending: return True for pending in self.node2pending.values(): if pending: return True return False
python
def has_pending(self): """Return True if there are pending test items This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active". """ if self.pending: return True for pending in self.node2pending.values(): if pending: return True return False
[ "def", "has_pending", "(", "self", ")", ":", "if", "self", ".", "pending", ":", "return", "True", "for", "pending", "in", "self", ".", "node2pending", ".", "values", "(", ")", ":", "if", "pending", ":", "return", "True", "return", "False" ]
Return True if there are pending test items This indicates that collection has finished and nodes are still processing test items, so this can be thought of as "the scheduler is active".
[ "Return", "True", "if", "there", "are", "pending", "test", "items" ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L96-L108
train
219,521
pytest-dev/pytest-xdist
xdist/scheduler/load.py
LoadScheduling.check_schedule
def check_schedule(self, node, duration=0): """Maybe schedule new items on the node If there are any globally pending nodes left then this will check if the given node should be given any more tests. The ``duration`` of the last test is optionally used as a heuristic to influence how many tests the node is assigned. """ if node.shutting_down: return if self.pending: # how many nodes do we have? num_nodes = len(self.node2pending) # if our node goes below a heuristic minimum, fill it out to # heuristic maximum items_per_node_min = max(2, len(self.pending) // num_nodes // 4) items_per_node_max = max(2, len(self.pending) // num_nodes // 2) node_pending = self.node2pending[node] if len(node_pending) < items_per_node_min: if duration >= 0.1 and len(node_pending) >= 2: # seems the node is doing long-running tests # and has enough items to continue # so let's rather wait with sending new items return num_send = items_per_node_max - len(node_pending) self._send_tests(node, num_send) else: node.shutdown() self.log("num items waiting for node:", len(self.pending))
python
def check_schedule(self, node, duration=0): """Maybe schedule new items on the node If there are any globally pending nodes left then this will check if the given node should be given any more tests. The ``duration`` of the last test is optionally used as a heuristic to influence how many tests the node is assigned. """ if node.shutting_down: return if self.pending: # how many nodes do we have? num_nodes = len(self.node2pending) # if our node goes below a heuristic minimum, fill it out to # heuristic maximum items_per_node_min = max(2, len(self.pending) // num_nodes // 4) items_per_node_max = max(2, len(self.pending) // num_nodes // 2) node_pending = self.node2pending[node] if len(node_pending) < items_per_node_min: if duration >= 0.1 and len(node_pending) >= 2: # seems the node is doing long-running tests # and has enough items to continue # so let's rather wait with sending new items return num_send = items_per_node_max - len(node_pending) self._send_tests(node, num_send) else: node.shutdown() self.log("num items waiting for node:", len(self.pending))
[ "def", "check_schedule", "(", "self", ",", "node", ",", "duration", "=", "0", ")", ":", "if", "node", ".", "shutting_down", ":", "return", "if", "self", ".", "pending", ":", "# how many nodes do we have?", "num_nodes", "=", "len", "(", "self", ".", "node2p...
Maybe schedule new items on the node If there are any globally pending nodes left then this will check if the given node should be given any more tests. The ``duration`` of the last test is optionally used as a heuristic to influence how many tests the node is assigned.
[ "Maybe", "schedule", "new", "items", "on", "the", "node" ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L154-L184
train
219,522
pytest-dev/pytest-xdist
xdist/scheduler/load.py
LoadScheduling.remove_node
def remove_node(self, node): """Remove a node from the scheduler This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the ``DSession.worker_workerfinished`` and ``DSession.worker_errordown`` hooks. Return the item which was being executing while the node crashed or None if the node has no more pending items. """ pending = self.node2pending.pop(node) if not pending: return # The node crashed, reassing pending items crashitem = self.collection[pending.pop(0)] self.pending.extend(pending) for node in self.node2pending: self.check_schedule(node) return crashitem
python
def remove_node(self, node): """Remove a node from the scheduler This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the ``DSession.worker_workerfinished`` and ``DSession.worker_errordown`` hooks. Return the item which was being executing while the node crashed or None if the node has no more pending items. """ pending = self.node2pending.pop(node) if not pending: return # The node crashed, reassing pending items crashitem = self.collection[pending.pop(0)] self.pending.extend(pending) for node in self.node2pending: self.check_schedule(node) return crashitem
[ "def", "remove_node", "(", "self", ",", "node", ")", ":", "pending", "=", "self", ".", "node2pending", ".", "pop", "(", "node", ")", "if", "not", "pending", ":", "return", "# The node crashed, reassing pending items", "crashitem", "=", "self", ".", "collection...
Remove a node from the scheduler This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the ``DSession.worker_workerfinished`` and ``DSession.worker_errordown`` hooks. Return the item which was being executing while the node crashed or None if the node has no more pending items.
[ "Remove", "a", "node", "from", "the", "scheduler" ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L186-L208
train
219,523
pytest-dev/pytest-xdist
xdist/scheduler/load.py
LoadScheduling.schedule
def schedule(self): """Initiate distribution of the test collection Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``.check_schedule()`` on all nodes so that newly added nodes will start to be used. This is called by the ``DSession.worker_collectionfinish`` hook if ``.collection_is_completed`` is True. """ assert self.collection_is_completed # Initial distribution already happened, reschedule on all nodes if self.collection is not None: for node in self.nodes: self.check_schedule(node) return # XXX allow nodes to have different collections if not self._check_nodes_have_same_collection(): self.log("**Different tests collected, aborting run**") return # Collections are identical, create the index of pending items. self.collection = list(self.node2collection.values())[0] self.pending[:] = range(len(self.collection)) if not self.collection: return # Send a batch of tests to run. If we don't have at least two # tests per node, we have to send them all so that we can send # shutdown signals and get all nodes working. initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes)) # distribute tests round-robin up to the batch size # (or until we run out) nodes = cycle(self.nodes) for i in range(initial_batch): self._send_tests(next(nodes), 1) if not self.pending: # initial distribution sent all tests, start node shutdown for node in self.nodes: node.shutdown()
python
def schedule(self): """Initiate distribution of the test collection Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``.check_schedule()`` on all nodes so that newly added nodes will start to be used. This is called by the ``DSession.worker_collectionfinish`` hook if ``.collection_is_completed`` is True. """ assert self.collection_is_completed # Initial distribution already happened, reschedule on all nodes if self.collection is not None: for node in self.nodes: self.check_schedule(node) return # XXX allow nodes to have different collections if not self._check_nodes_have_same_collection(): self.log("**Different tests collected, aborting run**") return # Collections are identical, create the index of pending items. self.collection = list(self.node2collection.values())[0] self.pending[:] = range(len(self.collection)) if not self.collection: return # Send a batch of tests to run. If we don't have at least two # tests per node, we have to send them all so that we can send # shutdown signals and get all nodes working. initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes)) # distribute tests round-robin up to the batch size # (or until we run out) nodes = cycle(self.nodes) for i in range(initial_batch): self._send_tests(next(nodes), 1) if not self.pending: # initial distribution sent all tests, start node shutdown for node in self.nodes: node.shutdown()
[ "def", "schedule", "(", "self", ")", ":", "assert", "self", ".", "collection_is_completed", "# Initial distribution already happened, reschedule on all nodes", "if", "self", ".", "collection", "is", "not", "None", ":", "for", "node", "in", "self", ".", "nodes", ":",...
Initiate distribution of the test collection Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``.check_schedule()`` on all nodes so that newly added nodes will start to be used. This is called by the ``DSession.worker_collectionfinish`` hook if ``.collection_is_completed`` is True.
[ "Initiate", "distribution", "of", "the", "test", "collection" ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L210-L254
train
219,524
pytest-dev/pytest-xdist
xdist/scheduler/load.py
LoadScheduling._check_nodes_have_same_collection
def _check_nodes_have_same_collection(self): """Return True if all nodes have collected the same items. If collections differ, this method returns False while logging the collection differences and posting collection errors to pytest_collectreport hook. """ node_collection_items = list(self.node2collection.items()) first_node, col = node_collection_items[0] same_collection = True for node, collection in node_collection_items[1:]: msg = report_collection_diff( col, collection, first_node.gateway.id, node.gateway.id ) if msg: same_collection = False self.log(msg) if self.config is not None: rep = CollectReport( node.gateway.id, "failed", longrepr=msg, result=[] ) self.config.hook.pytest_collectreport(report=rep) return same_collection
python
def _check_nodes_have_same_collection(self): """Return True if all nodes have collected the same items. If collections differ, this method returns False while logging the collection differences and posting collection errors to pytest_collectreport hook. """ node_collection_items = list(self.node2collection.items()) first_node, col = node_collection_items[0] same_collection = True for node, collection in node_collection_items[1:]: msg = report_collection_diff( col, collection, first_node.gateway.id, node.gateway.id ) if msg: same_collection = False self.log(msg) if self.config is not None: rep = CollectReport( node.gateway.id, "failed", longrepr=msg, result=[] ) self.config.hook.pytest_collectreport(report=rep) return same_collection
[ "def", "_check_nodes_have_same_collection", "(", "self", ")", ":", "node_collection_items", "=", "list", "(", "self", ".", "node2collection", ".", "items", "(", ")", ")", "first_node", ",", "col", "=", "node_collection_items", "[", "0", "]", "same_collection", "...
Return True if all nodes have collected the same items. If collections differ, this method returns False while logging the collection differences and posting collection errors to pytest_collectreport hook.
[ "Return", "True", "if", "all", "nodes", "have", "collected", "the", "same", "items", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L263-L286
train
219,525
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.loop_once
def loop_once(self): """Process one callback from one of the workers.""" while 1: if not self._active_nodes: # If everything has died stop looping self.triggershutdown() raise RuntimeError("Unexpectedly no active workers available") try: eventcall = self.queue.get(timeout=2.0) break except Empty: continue callname, kwargs = eventcall assert callname, kwargs method = "worker_" + callname call = getattr(self, method) self.log("calling method", method, kwargs) call(**kwargs) if self.sched.tests_finished: self.triggershutdown()
python
def loop_once(self): """Process one callback from one of the workers.""" while 1: if not self._active_nodes: # If everything has died stop looping self.triggershutdown() raise RuntimeError("Unexpectedly no active workers available") try: eventcall = self.queue.get(timeout=2.0) break except Empty: continue callname, kwargs = eventcall assert callname, kwargs method = "worker_" + callname call = getattr(self, method) self.log("calling method", method, kwargs) call(**kwargs) if self.sched.tests_finished: self.triggershutdown()
[ "def", "loop_once", "(", "self", ")", ":", "while", "1", ":", "if", "not", "self", ".", "_active_nodes", ":", "# If everything has died stop looping", "self", ".", "triggershutdown", "(", ")", "raise", "RuntimeError", "(", "\"Unexpectedly no active workers available\"...
Process one callback from one of the workers.
[ "Process", "one", "callback", "from", "one", "of", "the", "workers", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L121-L140
train
219,526
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_workerready
def worker_workerready(self, node, workerinfo): """Emitted when a node first starts up. This adds the node to the scheduler, nodes continue with collection without any further input. """ node.workerinfo = workerinfo node.workerinfo["id"] = node.gateway.id node.workerinfo["spec"] = node.gateway.spec # TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo node.slaveinfo = node.workerinfo self.config.hook.pytest_testnodeready(node=node) if self.shuttingdown: node.shutdown() else: self.sched.add_node(node)
python
def worker_workerready(self, node, workerinfo): """Emitted when a node first starts up. This adds the node to the scheduler, nodes continue with collection without any further input. """ node.workerinfo = workerinfo node.workerinfo["id"] = node.gateway.id node.workerinfo["spec"] = node.gateway.spec # TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo node.slaveinfo = node.workerinfo self.config.hook.pytest_testnodeready(node=node) if self.shuttingdown: node.shutdown() else: self.sched.add_node(node)
[ "def", "worker_workerready", "(", "self", ",", "node", ",", "workerinfo", ")", ":", "node", ".", "workerinfo", "=", "workerinfo", "node", ".", "workerinfo", "[", "\"id\"", "]", "=", "node", ".", "gateway", ".", "id", "node", ".", "workerinfo", "[", "\"sp...
Emitted when a node first starts up. This adds the node to the scheduler, nodes continue with collection without any further input.
[ "Emitted", "when", "a", "node", "first", "starts", "up", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L146-L163
train
219,527
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_workerfinished
def worker_workerfinished(self, node): """Emitted when node executes its pytest_sessionfinish hook. Removes the node from the scheduler. The node might not be in the scheduler if it had not emitted workerready before shutdown was triggered. """ self.config.hook.pytest_testnodedown(node=node, error=None) if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt self.shouldstop = "%s received keyboard-interrupt" % (node,) self.worker_errordown(node, "keyboard-interrupt") return if node in self.sched.nodes: crashitem = self.sched.remove_node(node) assert not crashitem, (crashitem, node) self._active_nodes.remove(node)
python
def worker_workerfinished(self, node): """Emitted when node executes its pytest_sessionfinish hook. Removes the node from the scheduler. The node might not be in the scheduler if it had not emitted workerready before shutdown was triggered. """ self.config.hook.pytest_testnodedown(node=node, error=None) if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt self.shouldstop = "%s received keyboard-interrupt" % (node,) self.worker_errordown(node, "keyboard-interrupt") return if node in self.sched.nodes: crashitem = self.sched.remove_node(node) assert not crashitem, (crashitem, node) self._active_nodes.remove(node)
[ "def", "worker_workerfinished", "(", "self", ",", "node", ")", ":", "self", ".", "config", ".", "hook", ".", "pytest_testnodedown", "(", "node", "=", "node", ",", "error", "=", "None", ")", "if", "node", ".", "workeroutput", "[", "\"exitstatus\"", "]", "...
Emitted when node executes its pytest_sessionfinish hook. Removes the node from the scheduler. The node might not be in the scheduler if it had not emitted workerready before shutdown was triggered.
[ "Emitted", "when", "node", "executes", "its", "pytest_sessionfinish", "hook", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L165-L181
train
219,528
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_errordown
def worker_errordown(self, node, error): """Emitted by the WorkerController when a node dies.""" self.config.hook.pytest_testnodedown(node=node, error=error) try: crashitem = self.sched.remove_node(node) except KeyError: pass else: if crashitem: self.handle_crashitem(crashitem, node) self._failed_nodes_count += 1 maximum_reached = ( self._max_worker_restart is not None and self._failed_nodes_count > self._max_worker_restart ) if maximum_reached: if self._max_worker_restart == 0: msg = "Worker restarting disabled" else: msg = "Maximum crashed workers reached: %d" % self._max_worker_restart self.report_line(msg) else: self.report_line("Replacing crashed worker %s" % node.gateway.id) self._clone_node(node) self._active_nodes.remove(node)
python
def worker_errordown(self, node, error): """Emitted by the WorkerController when a node dies.""" self.config.hook.pytest_testnodedown(node=node, error=error) try: crashitem = self.sched.remove_node(node) except KeyError: pass else: if crashitem: self.handle_crashitem(crashitem, node) self._failed_nodes_count += 1 maximum_reached = ( self._max_worker_restart is not None and self._failed_nodes_count > self._max_worker_restart ) if maximum_reached: if self._max_worker_restart == 0: msg = "Worker restarting disabled" else: msg = "Maximum crashed workers reached: %d" % self._max_worker_restart self.report_line(msg) else: self.report_line("Replacing crashed worker %s" % node.gateway.id) self._clone_node(node) self._active_nodes.remove(node)
[ "def", "worker_errordown", "(", "self", ",", "node", ",", "error", ")", ":", "self", ".", "config", ".", "hook", ".", "pytest_testnodedown", "(", "node", "=", "node", ",", "error", "=", "error", ")", "try", ":", "crashitem", "=", "self", ".", "sched", ...
Emitted by the WorkerController when a node dies.
[ "Emitted", "by", "the", "WorkerController", "when", "a", "node", "dies", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L183-L208
train
219,529
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_collectionfinish
def worker_collectionfinish(self, node, ids): """worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler to schedule the collected items. When initiating scheduling the first time it logs which scheduler is in use. """ if self.shuttingdown: return self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids) # tell session which items were effectively collected otherwise # the master node will finish the session with EXIT_NOTESTSCOLLECTED self._session.testscollected = len(ids) self.sched.add_node_collection(node, ids) if self.terminal: self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids))) if self.sched.collection_is_completed: if self.terminal and not self.sched.has_pending: self.trdist.ensure_show_status() self.terminal.write_line("") if self.config.option.verbose > 0: self.terminal.write_line( "scheduling tests via %s" % (self.sched.__class__.__name__) ) self.sched.schedule()
python
def worker_collectionfinish(self, node, ids): """worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler to schedule the collected items. When initiating scheduling the first time it logs which scheduler is in use. """ if self.shuttingdown: return self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids) # tell session which items were effectively collected otherwise # the master node will finish the session with EXIT_NOTESTSCOLLECTED self._session.testscollected = len(ids) self.sched.add_node_collection(node, ids) if self.terminal: self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids))) if self.sched.collection_is_completed: if self.terminal and not self.sched.has_pending: self.trdist.ensure_show_status() self.terminal.write_line("") if self.config.option.verbose > 0: self.terminal.write_line( "scheduling tests via %s" % (self.sched.__class__.__name__) ) self.sched.schedule()
[ "def", "worker_collectionfinish", "(", "self", ",", "node", ",", "ids", ")", ":", "if", "self", ".", "shuttingdown", ":", "return", "self", ".", "config", ".", "hook", ".", "pytest_xdist_node_collection_finished", "(", "node", "=", "node", ",", "ids", "=", ...
worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler to schedule the collected items. When initiating scheduling the first time it logs which scheduler is in use.
[ "worker", "has", "finished", "test", "collection", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L210-L236
train
219,530
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_logstart
def worker_logstart(self, node, nodeid, location): """Emitted when a node calls the pytest_runtest_logstart hook.""" self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location)
python
def worker_logstart(self, node, nodeid, location): """Emitted when a node calls the pytest_runtest_logstart hook.""" self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location)
[ "def", "worker_logstart", "(", "self", ",", "node", ",", "nodeid", ",", "location", ")", ":", "self", ".", "config", ".", "hook", ".", "pytest_runtest_logstart", "(", "nodeid", "=", "nodeid", ",", "location", "=", "location", ")" ]
Emitted when a node calls the pytest_runtest_logstart hook.
[ "Emitted", "when", "a", "node", "calls", "the", "pytest_runtest_logstart", "hook", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L238-L240
train
219,531
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_logfinish
def worker_logfinish(self, node, nodeid, location): """Emitted when a node calls the pytest_runtest_logfinish hook.""" self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location)
python
def worker_logfinish(self, node, nodeid, location): """Emitted when a node calls the pytest_runtest_logfinish hook.""" self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location)
[ "def", "worker_logfinish", "(", "self", ",", "node", ",", "nodeid", ",", "location", ")", ":", "self", ".", "config", ".", "hook", ".", "pytest_runtest_logfinish", "(", "nodeid", "=", "nodeid", ",", "location", "=", "location", ")" ]
Emitted when a node calls the pytest_runtest_logfinish hook.
[ "Emitted", "when", "a", "node", "calls", "the", "pytest_runtest_logfinish", "hook", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L242-L244
train
219,532
pytest-dev/pytest-xdist
xdist/dsession.py
DSession.worker_collectreport
def worker_collectreport(self, node, rep): """Emitted when a node calls the pytest_collectreport hook. Because we only need the report when there's a failure/skip, as optimization we only expect to receive failed/skipped reports from workers (#330). """ assert not rep.passed self._failed_worker_collectreport(node, rep)
python
def worker_collectreport(self, node, rep): """Emitted when a node calls the pytest_collectreport hook. Because we only need the report when there's a failure/skip, as optimization we only expect to receive failed/skipped reports from workers (#330). """ assert not rep.passed self._failed_worker_collectreport(node, rep)
[ "def", "worker_collectreport", "(", "self", ",", "node", ",", "rep", ")", ":", "assert", "not", "rep", ".", "passed", "self", ".", "_failed_worker_collectreport", "(", "node", ",", "rep", ")" ]
Emitted when a node calls the pytest_collectreport hook. Because we only need the report when there's a failure/skip, as optimization we only expect to receive failed/skipped reports from workers (#330).
[ "Emitted", "when", "a", "node", "calls", "the", "pytest_collectreport", "hook", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L260-L267
train
219,533
pytest-dev/pytest-xdist
xdist/dsession.py
DSession._clone_node
def _clone_node(self, node): """Return new node based on an existing one. This is normally for when a node dies, this will copy the spec of the existing node and create a new one with a new id. The new node will have been setup so it will start calling the "worker_*" hooks and do work soon. """ spec = node.gateway.spec spec.id = None self.nodemanager.group.allocate_id(spec) node = self.nodemanager.setup_node(spec, self.queue.put) self._active_nodes.add(node) return node
python
def _clone_node(self, node): """Return new node based on an existing one. This is normally for when a node dies, this will copy the spec of the existing node and create a new one with a new id. The new node will have been setup so it will start calling the "worker_*" hooks and do work soon. """ spec = node.gateway.spec spec.id = None self.nodemanager.group.allocate_id(spec) node = self.nodemanager.setup_node(spec, self.queue.put) self._active_nodes.add(node) return node
[ "def", "_clone_node", "(", "self", ",", "node", ")", ":", "spec", "=", "node", ".", "gateway", ".", "spec", "spec", ".", "id", "=", "None", "self", ".", "nodemanager", ".", "group", ".", "allocate_id", "(", "spec", ")", "node", "=", "self", ".", "n...
Return new node based on an existing one. This is normally for when a node dies, this will copy the spec of the existing node and create a new one with a new id. The new node will have been setup so it will start calling the "worker_*" hooks and do work soon.
[ "Return", "new", "node", "based", "on", "an", "existing", "one", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L279-L292
train
219,534
pytest-dev/pytest-xdist
xdist/workermanage.py
NodeManager.rsync_roots
def rsync_roots(self, gateway): """Rsync the set of roots to the node's gateway cwd.""" if self.roots: for root in self.roots: self.rsync(gateway, root, **self.rsyncoptions)
python
def rsync_roots(self, gateway): """Rsync the set of roots to the node's gateway cwd.""" if self.roots: for root in self.roots: self.rsync(gateway, root, **self.rsyncoptions)
[ "def", "rsync_roots", "(", "self", ",", "gateway", ")", ":", "if", "self", ".", "roots", ":", "for", "root", "in", "self", ".", "roots", ":", "self", ".", "rsync", "(", "gateway", ",", "root", ",", "*", "*", "self", ".", "rsyncoptions", ")" ]
Rsync the set of roots to the node's gateway cwd.
[ "Rsync", "the", "set", "of", "roots", "to", "the", "node", "s", "gateway", "cwd", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L53-L57
train
219,535
pytest-dev/pytest-xdist
xdist/workermanage.py
NodeManager._getrsyncoptions
def _getrsyncoptions(self): """Get options to be passed for rsync.""" ignores = list(self.DEFAULT_IGNORES) ignores += self.config.option.rsyncignore ignores += self.config.getini("rsyncignore") return {"ignores": ignores, "verbose": self.config.option.verbose}
python
def _getrsyncoptions(self): """Get options to be passed for rsync.""" ignores = list(self.DEFAULT_IGNORES) ignores += self.config.option.rsyncignore ignores += self.config.getini("rsyncignore") return {"ignores": ignores, "verbose": self.config.option.verbose}
[ "def", "_getrsyncoptions", "(", "self", ")", ":", "ignores", "=", "list", "(", "self", ".", "DEFAULT_IGNORES", ")", "ignores", "+=", "self", ".", "config", ".", "option", ".", "rsyncignore", "ignores", "+=", "self", ".", "config", ".", "getini", "(", "\"...
Get options to be passed for rsync.
[ "Get", "options", "to", "be", "passed", "for", "rsync", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L109-L115
train
219,536
pytest-dev/pytest-xdist
xdist/workermanage.py
WorkerController.sendcommand
def sendcommand(self, name, **kwargs): """ send a named parametrized command to the other side. """ self.log("sending command %s(**%s)" % (name, kwargs)) self.channel.send((name, kwargs))
python
def sendcommand(self, name, **kwargs): """ send a named parametrized command to the other side. """ self.log("sending command %s(**%s)" % (name, kwargs)) self.channel.send((name, kwargs))
[ "def", "sendcommand", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "\"sending command %s(**%s)\"", "%", "(", "name", ",", "kwargs", ")", ")", "self", ".", "channel", ".", "send", "(", "(", "name", ",", "kwargs...
send a named parametrized command to the other side.
[ "send", "a", "named", "parametrized", "command", "to", "the", "other", "side", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L284-L287
train
219,537
pytest-dev/pytest-xdist
xdist/workermanage.py
WorkerController.process_from_remote
def process_from_remote(self, eventcall): # noqa too complex """ this gets called for each object we receive from the other side and if the channel closes. Note that channel callbacks run in the receiver thread of execnet gateways - we need to avoid raising exceptions or doing heavy work. """ try: if eventcall == self.ENDMARK: err = self.channel._getremoteerror() if not self._down: if not err or isinstance(err, EOFError): err = "Not properly terminated" # lost connection? self.notify_inproc("errordown", node=self, error=err) self._down = True return eventname, kwargs = eventcall if eventname in ("collectionstart",): self.log("ignoring %s(%s)" % (eventname, kwargs)) elif eventname == "workerready": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "workerfinished": self._down = True self.workeroutput = self.slaveoutput = kwargs["workeroutput"] self.notify_inproc("workerfinished", node=self) elif eventname in ("logstart", "logfinish"): self.notify_inproc(eventname, node=self, **kwargs) elif eventname in ("testreport", "collectreport", "teardownreport"): item_index = kwargs.pop("item_index", None) rep = self.config.hook.pytest_report_from_serializable( config=self.config, data=kwargs["data"] ) if item_index is not None: rep.item_index = item_index self.notify_inproc(eventname, node=self, rep=rep) elif eventname == "collectionfinish": self.notify_inproc(eventname, node=self, ids=kwargs["ids"]) elif eventname == "runtest_protocol_complete": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "logwarning": self.notify_inproc( eventname, message=kwargs["message"], code=kwargs["code"], nodeid=kwargs["nodeid"], fslocation=kwargs["nodeid"], ) elif eventname == "warning_captured": warning_message = unserialize_warning_message( kwargs["warning_message_data"] ) self.notify_inproc( eventname, warning_message=warning_message, when=kwargs["when"], item=kwargs["item"], ) else: raise ValueError("unknown event: %s" % (eventname,)) except KeyboardInterrupt: # should not land in receiver-thread raise except: # noqa from _pytest._code import ExceptionInfo # ExceptionInfo API changed in pytest 4.1 if hasattr(ExceptionInfo, "from_current"): excinfo = ExceptionInfo.from_current() else: excinfo = ExceptionInfo() print("!" * 20, excinfo) self.config.notify_exception(excinfo) self.shutdown() self.notify_inproc("errordown", node=self, error=excinfo)
python
def process_from_remote(self, eventcall): # noqa too complex """ this gets called for each object we receive from the other side and if the channel closes. Note that channel callbacks run in the receiver thread of execnet gateways - we need to avoid raising exceptions or doing heavy work. """ try: if eventcall == self.ENDMARK: err = self.channel._getremoteerror() if not self._down: if not err or isinstance(err, EOFError): err = "Not properly terminated" # lost connection? self.notify_inproc("errordown", node=self, error=err) self._down = True return eventname, kwargs = eventcall if eventname in ("collectionstart",): self.log("ignoring %s(%s)" % (eventname, kwargs)) elif eventname == "workerready": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "workerfinished": self._down = True self.workeroutput = self.slaveoutput = kwargs["workeroutput"] self.notify_inproc("workerfinished", node=self) elif eventname in ("logstart", "logfinish"): self.notify_inproc(eventname, node=self, **kwargs) elif eventname in ("testreport", "collectreport", "teardownreport"): item_index = kwargs.pop("item_index", None) rep = self.config.hook.pytest_report_from_serializable( config=self.config, data=kwargs["data"] ) if item_index is not None: rep.item_index = item_index self.notify_inproc(eventname, node=self, rep=rep) elif eventname == "collectionfinish": self.notify_inproc(eventname, node=self, ids=kwargs["ids"]) elif eventname == "runtest_protocol_complete": self.notify_inproc(eventname, node=self, **kwargs) elif eventname == "logwarning": self.notify_inproc( eventname, message=kwargs["message"], code=kwargs["code"], nodeid=kwargs["nodeid"], fslocation=kwargs["nodeid"], ) elif eventname == "warning_captured": warning_message = unserialize_warning_message( kwargs["warning_message_data"] ) self.notify_inproc( eventname, warning_message=warning_message, when=kwargs["when"], item=kwargs["item"], ) else: raise ValueError("unknown event: %s" % (eventname,)) except KeyboardInterrupt: # should not land in receiver-thread raise except: # noqa from _pytest._code import ExceptionInfo # ExceptionInfo API changed in pytest 4.1 if hasattr(ExceptionInfo, "from_current"): excinfo = ExceptionInfo.from_current() else: excinfo = ExceptionInfo() print("!" * 20, excinfo) self.config.notify_exception(excinfo) self.shutdown() self.notify_inproc("errordown", node=self, error=excinfo)
[ "def", "process_from_remote", "(", "self", ",", "eventcall", ")", ":", "# noqa too complex", "try", ":", "if", "eventcall", "==", "self", ".", "ENDMARK", ":", "err", "=", "self", ".", "channel", ".", "_getremoteerror", "(", ")", "if", "not", "self", ".", ...
this gets called for each object we receive from the other side and if the channel closes. Note that channel callbacks run in the receiver thread of execnet gateways - we need to avoid raising exceptions or doing heavy work.
[ "this", "gets", "called", "for", "each", "object", "we", "receive", "from", "the", "other", "side", "and", "if", "the", "channel", "closes", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L293-L367
train
219,538
pytest-dev/pytest-xdist
xdist/report.py
report_collection_diff
def report_collection_diff(from_collection, to_collection, from_id, to_id): """Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal. """ if from_collection == to_collection: return None diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id) error_message = ( u"Different tests were collected between {from_id} and {to_id}. " u"The difference is:\n" u"{diff}" ).format(from_id=from_id, to_id=to_id, diff="\n".join(diff)) msg = "\n".join([x.rstrip() for x in error_message.split("\n")]) return msg
python
def report_collection_diff(from_collection, to_collection, from_id, to_id): """Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal. """ if from_collection == to_collection: return None diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id) error_message = ( u"Different tests were collected between {from_id} and {to_id}. " u"The difference is:\n" u"{diff}" ).format(from_id=from_id, to_id=to_id, diff="\n".join(diff)) msg = "\n".join([x.rstrip() for x in error_message.split("\n")]) return msg
[ "def", "report_collection_diff", "(", "from_collection", ",", "to_collection", ",", "from_id", ",", "to_id", ")", ":", "if", "from_collection", "==", "to_collection", ":", "return", "None", "diff", "=", "unified_diff", "(", "from_collection", ",", "to_collection", ...
Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal.
[ "Report", "the", "collected", "test", "difference", "between", "two", "nodes", "." ]
9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/report.py#L5-L21
train
219,539
ivelum/djangoql
djangoql/queryset.py
apply_search
def apply_search(queryset, search, schema=None): """ Applies search written in DjangoQL mini-language to given queryset """ ast = DjangoQLParser().parse(search) schema = schema or DjangoQLSchema schema_instance = schema(queryset.model) schema_instance.validate(ast) return queryset.filter(build_filter(ast, schema_instance))
python
def apply_search(queryset, search, schema=None): """ Applies search written in DjangoQL mini-language to given queryset """ ast = DjangoQLParser().parse(search) schema = schema or DjangoQLSchema schema_instance = schema(queryset.model) schema_instance.validate(ast) return queryset.filter(build_filter(ast, schema_instance))
[ "def", "apply_search", "(", "queryset", ",", "search", ",", "schema", "=", "None", ")", ":", "ast", "=", "DjangoQLParser", "(", ")", ".", "parse", "(", "search", ")", "schema", "=", "schema", "or", "DjangoQLSchema", "schema_instance", "=", "schema", "(", ...
Applies search written in DjangoQL mini-language to given queryset
[ "Applies", "search", "written", "in", "DjangoQL", "mini", "-", "language", "to", "given", "queryset" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/queryset.py#L32-L40
train
219,540
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_options
def get_options(self): """ Override this method to provide custom suggestion options """ choices = self._field_choices() if choices: return [c[1] for c in choices] else: return self.model.objects.\ order_by(self.name).\ values_list(self.name, flat=True)
python
def get_options(self): """ Override this method to provide custom suggestion options """ choices = self._field_choices() if choices: return [c[1] for c in choices] else: return self.model.objects.\ order_by(self.name).\ values_list(self.name, flat=True)
[ "def", "get_options", "(", "self", ")", ":", "choices", "=", "self", ".", "_field_choices", "(", ")", "if", "choices", ":", "return", "[", "c", "[", "1", "]", "for", "c", "in", "choices", "]", "else", ":", "return", "self", ".", "model", ".", "obje...
Override this method to provide custom suggestion options
[ "Override", "this", "method", "to", "provide", "custom", "suggestion", "options" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L55-L65
train
219,541
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_lookup_value
def get_lookup_value(self, value): """ Override this method to convert displayed values to lookup values """ choices = self._field_choices() if choices: if isinstance(value, list): return [c[0] for c in choices if c[1] in value] else: for c in choices: if c[1] == value: return c[0] return value
python
def get_lookup_value(self, value): """ Override this method to convert displayed values to lookup values """ choices = self._field_choices() if choices: if isinstance(value, list): return [c[0] for c in choices if c[1] in value] else: for c in choices: if c[1] == value: return c[0] return value
[ "def", "get_lookup_value", "(", "self", ",", "value", ")", ":", "choices", "=", "self", ".", "_field_choices", "(", ")", "if", "choices", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "c", "[", "0", "]", "for", "c", "...
Override this method to convert displayed values to lookup values
[ "Override", "this", "method", "to", "convert", "displayed", "values", "to", "lookup", "values" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L73-L85
train
219,542
ivelum/djangoql
djangoql/schema.py
DjangoQLField.get_operator
def get_operator(self, operator): """ Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this comparison needs to be inverted """ op = { '=': '', '>': '__gt', '>=': '__gte', '<': '__lt', '<=': '__lte', '~': '__icontains', 'in': '__in', }.get(operator) if op is not None: return op, False op = { '!=': '', '!~': '__icontains', 'not in': '__in', }[operator] return op, True
python
def get_operator(self, operator): """ Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this comparison needs to be inverted """ op = { '=': '', '>': '__gt', '>=': '__gte', '<': '__lt', '<=': '__lte', '~': '__icontains', 'in': '__in', }.get(operator) if op is not None: return op, False op = { '!=': '', '!~': '__icontains', 'not in': '__in', }[operator] return op, True
[ "def", "get_operator", "(", "self", ",", "operator", ")", ":", "op", "=", "{", "'='", ":", "''", ",", "'>'", ":", "'__gt'", ",", "'>='", ":", "'__gte'", ",", "'<'", ":", "'__lt'", ",", "'<='", ":", "'__lte'", ",", "'~'", ":", "'__icontains'", ",", ...
Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this comparison needs to be inverted
[ "Get", "a", "comparison", "suffix", "to", "be", "used", "in", "Django", "ORM", "&", "inversion", "flag", "for", "it" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L87-L112
train
219,543
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.introspect
def introspect(self, model, exclude=()): """ Start with given model and recursively walk through its relationships. Returns a dict with all model labels and their fields found. """ result = {} open_set = deque([model]) closed_set = list(exclude) while open_set: model = open_set.popleft() model_label = self.model_label(model) if model_label in closed_set: continue model_fields = OrderedDict() for field in self.get_fields(model): if not isinstance(field, DjangoQLField): field = self.get_field_instance(model, field) if not field: continue if isinstance(field, RelationField): if field.relation not in closed_set: model_fields[field.name] = field open_set.append(field.related_model) else: model_fields[field.name] = field result[model_label] = model_fields closed_set.append(model_label) return result
python
def introspect(self, model, exclude=()): """ Start with given model and recursively walk through its relationships. Returns a dict with all model labels and their fields found. """ result = {} open_set = deque([model]) closed_set = list(exclude) while open_set: model = open_set.popleft() model_label = self.model_label(model) if model_label in closed_set: continue model_fields = OrderedDict() for field in self.get_fields(model): if not isinstance(field, DjangoQLField): field = self.get_field_instance(model, field) if not field: continue if isinstance(field, RelationField): if field.relation not in closed_set: model_fields[field.name] = field open_set.append(field.related_model) else: model_fields[field.name] = field result[model_label] = model_fields closed_set.append(model_label) return result
[ "def", "introspect", "(", "self", ",", "model", ",", "exclude", "=", "(", ")", ")", ":", "result", "=", "{", "}", "open_set", "=", "deque", "(", "[", "model", "]", ")", "closed_set", "=", "list", "(", "exclude", ")", "while", "open_set", ":", "mode...
Start with given model and recursively walk through its relationships. Returns a dict with all model labels and their fields found.
[ "Start", "with", "given", "model", "and", "recursively", "walk", "through", "its", "relationships", "." ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L332-L365
train
219,544
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.get_fields
def get_fields(self, model): """ By default, returns all field names of a given model. Override this method to limit field options. You can either return a plain list of field names from it, like ['id', 'name'], or call .super() and exclude unwanted fields from its result. """ return sorted( [f.name for f in model._meta.get_fields() if f.name != 'password'] )
python
def get_fields(self, model): """ By default, returns all field names of a given model. Override this method to limit field options. You can either return a plain list of field names from it, like ['id', 'name'], or call .super() and exclude unwanted fields from its result. """ return sorted( [f.name for f in model._meta.get_fields() if f.name != 'password'] )
[ "def", "get_fields", "(", "self", ",", "model", ")", ":", "return", "sorted", "(", "[", "f", ".", "name", "for", "f", "in", "model", ".", "_meta", ".", "get_fields", "(", ")", "if", "f", ".", "name", "!=", "'password'", "]", ")" ]
By default, returns all field names of a given model. Override this method to limit field options. You can either return a plain list of field names from it, like ['id', 'name'], or call .super() and exclude unwanted fields from its result.
[ "By", "default", "returns", "all", "field", "names", "of", "a", "given", "model", "." ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L367-L377
train
219,545
ivelum/djangoql
djangoql/schema.py
DjangoQLSchema.validate
def validate(self, node): """ Validate DjangoQL AST tree vs. current schema """ assert isinstance(node, Node) if isinstance(node.operator, Logical): self.validate(node.left) self.validate(node.right) return assert isinstance(node.left, Name) assert isinstance(node.operator, Comparison) assert isinstance(node.right, (Const, List)) # Check that field and value types are compatible field = self.resolve_name(node.left) value = node.right.value if field is None: if value is not None: raise DjangoQLSchemaError( 'Related model %s can be compared to None only, but not to ' '%s' % (node.left.value, type(value).__name__) ) else: values = value if isinstance(node.right, List) else [value] for v in values: field.validate(v)
python
def validate(self, node): """ Validate DjangoQL AST tree vs. current schema """ assert isinstance(node, Node) if isinstance(node.operator, Logical): self.validate(node.left) self.validate(node.right) return assert isinstance(node.left, Name) assert isinstance(node.operator, Comparison) assert isinstance(node.right, (Const, List)) # Check that field and value types are compatible field = self.resolve_name(node.left) value = node.right.value if field is None: if value is not None: raise DjangoQLSchemaError( 'Related model %s can be compared to None only, but not to ' '%s' % (node.left.value, type(value).__name__) ) else: values = value if isinstance(node.right, List) else [value] for v in values: field.validate(v)
[ "def", "validate", "(", "self", ",", "node", ")", ":", "assert", "isinstance", "(", "node", ",", "Node", ")", "if", "isinstance", "(", "node", ".", "operator", ",", "Logical", ")", ":", "self", ".", "validate", "(", "node", ".", "left", ")", "self", ...
Validate DjangoQL AST tree vs. current schema
[ "Validate", "DjangoQL", "AST", "tree", "vs", ".", "current", "schema" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L454-L479
train
219,546
ivelum/djangoql
djangoql/lexer.py
DjangoQLLexer.find_column
def find_column(self, t): """ Returns token position in current text, starting from 1 """ cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators) if cr == -1: return t.lexpos + 1 return t.lexpos - cr
python
def find_column(self, t): """ Returns token position in current text, starting from 1 """ cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators) if cr == -1: return t.lexpos + 1 return t.lexpos - cr
[ "def", "find_column", "(", "self", ",", "t", ")", ":", "cr", "=", "max", "(", "self", ".", "text", ".", "rfind", "(", "l", ",", "0", ",", "t", ".", "lexpos", ")", "for", "l", "in", "self", ".", "line_terminators", ")", "if", "cr", "==", "-", ...
Returns token position in current text, starting from 1
[ "Returns", "token", "position", "in", "current", "text", "starting", "from", "1" ]
8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897
https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/lexer.py#L40-L47
train
219,547
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
execute_filter
async def execute_filter(filter_: FilterObj, args): """ Helper for executing filter :param filter_: :param args: :return: """ if filter_.is_async: return await filter_.filter(*args, **filter_.kwargs) else: return filter_.filter(*args, **filter_.kwargs)
python
async def execute_filter(filter_: FilterObj, args): """ Helper for executing filter :param filter_: :param args: :return: """ if filter_.is_async: return await filter_.filter(*args, **filter_.kwargs) else: return filter_.filter(*args, **filter_.kwargs)
[ "async", "def", "execute_filter", "(", "filter_", ":", "FilterObj", ",", "args", ")", ":", "if", "filter_", ".", "is_async", ":", "return", "await", "filter_", ".", "filter", "(", "*", "args", ",", "*", "*", "filter_", ".", "kwargs", ")", "else", ":", ...
Helper for executing filter :param filter_: :param args: :return:
[ "Helper", "for", "executing", "filter" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L47-L58
train
219,548
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
check_filters
async def check_filters(filters: typing.Iterable[FilterObj], args): """ Check list of filters :param filters: :param args: :return: """ data = {} if filters is not None: for filter_ in filters: f = await execute_filter(filter_, args) if not f: raise FilterNotPassed() elif isinstance(f, dict): data.update(f) return data
python
async def check_filters(filters: typing.Iterable[FilterObj], args): """ Check list of filters :param filters: :param args: :return: """ data = {} if filters is not None: for filter_ in filters: f = await execute_filter(filter_, args) if not f: raise FilterNotPassed() elif isinstance(f, dict): data.update(f) return data
[ "async", "def", "check_filters", "(", "filters", ":", "typing", ".", "Iterable", "[", "FilterObj", "]", ",", "args", ")", ":", "data", "=", "{", "}", "if", "filters", "is", "not", "None", ":", "for", "filter_", "in", "filters", ":", "f", "=", "await"...
Check list of filters :param filters: :param args: :return:
[ "Check", "list", "of", "filters" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77
train
219,549
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
AbstractFilter.validate
def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]: """ Validate and parse config. This method will be called by the filters factory when you bind this filter. Must be overridden. :param full_config: dict with arguments passed to handler registrar :return: Current filter config """ pass
python
def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]: """ Validate and parse config. This method will be called by the filters factory when you bind this filter. Must be overridden. :param full_config: dict with arguments passed to handler registrar :return: Current filter config """ pass
[ "def", "validate", "(", "cls", ",", "full_config", ":", "typing", ".", "Dict", "[", "str", ",", "typing", ".", "Any", "]", ")", "->", "typing", ".", "Optional", "[", "typing", ".", "Dict", "[", "str", ",", "typing", ".", "Any", "]", "]", ":", "pa...
Validate and parse config. This method will be called by the filters factory when you bind this filter. Must be overridden. :param full_config: dict with arguments passed to handler registrar :return: Current filter config
[ "Validate", "and", "parse", "config", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L136-L146
train
219,550
aiogram/aiogram
aiogram/dispatcher/filters/filters.py
AndFilter.check
async def check(self, *args): """ All filters must return a positive result :param args: :return: """ data = {} for target in self.targets: result = await target(*args) if not result: return False if isinstance(result, dict): data.update(result) if not data: return True return data
python
async def check(self, *args): """ All filters must return a positive result :param args: :return: """ data = {} for target in self.targets: result = await target(*args) if not result: return False if isinstance(result, dict): data.update(result) if not data: return True return data
[ "async", "def", "check", "(", "self", ",", "*", "args", ")", ":", "data", "=", "{", "}", "for", "target", "in", "self", ".", "targets", ":", "result", "=", "await", "target", "(", "*", "args", ")", "if", "not", "result", ":", "return", "False", "...
All filters must return a positive result :param args: :return:
[ "All", "filters", "must", "return", "a", "positive", "result" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L247-L263
train
219,551
aiogram/aiogram
examples/broadcast_example.py
send_message
async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool: """ Safe messages sender :param user_id: :param text: :param disable_notification: :return: """ try: await bot.send_message(user_id, text, disable_notification=disable_notification) except exceptions.BotBlocked: log.error(f"Target [ID:{user_id}]: blocked by user") except exceptions.ChatNotFound: log.error(f"Target [ID:{user_id}]: invalid user ID") except exceptions.RetryAfter as e: log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.") await asyncio.sleep(e.timeout) return await send_message(user_id, text) # Recursive call except exceptions.UserDeactivated: log.error(f"Target [ID:{user_id}]: user is deactivated") except exceptions.TelegramAPIError: log.exception(f"Target [ID:{user_id}]: failed") else: log.info(f"Target [ID:{user_id}]: success") return True return False
python
async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool: """ Safe messages sender :param user_id: :param text: :param disable_notification: :return: """ try: await bot.send_message(user_id, text, disable_notification=disable_notification) except exceptions.BotBlocked: log.error(f"Target [ID:{user_id}]: blocked by user") except exceptions.ChatNotFound: log.error(f"Target [ID:{user_id}]: invalid user ID") except exceptions.RetryAfter as e: log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.") await asyncio.sleep(e.timeout) return await send_message(user_id, text) # Recursive call except exceptions.UserDeactivated: log.error(f"Target [ID:{user_id}]: user is deactivated") except exceptions.TelegramAPIError: log.exception(f"Target [ID:{user_id}]: failed") else: log.info(f"Target [ID:{user_id}]: success") return True return False
[ "async", "def", "send_message", "(", "user_id", ":", "int", ",", "text", ":", "str", ",", "disable_notification", ":", "bool", "=", "False", ")", "->", "bool", ":", "try", ":", "await", "bot", ".", "send_message", "(", "user_id", ",", "text", ",", "dis...
Safe messages sender :param user_id: :param text: :param disable_notification: :return:
[ "Safe", "messages", "sender" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/broadcast_example.py#L26-L52
train
219,552
aiogram/aiogram
aiogram/types/message.py
Message.get_full_command
def get_full_command(self): """ Split command and args :return: tuple of (command, args) """ if self.is_command(): command, _, args = self.text.partition(' ') return command, args
python
def get_full_command(self): """ Split command and args :return: tuple of (command, args) """ if self.is_command(): command, _, args = self.text.partition(' ') return command, args
[ "def", "get_full_command", "(", "self", ")", ":", "if", "self", ".", "is_command", "(", ")", ":", "command", ",", "_", ",", "args", "=", "self", ".", "text", ".", "partition", "(", "' '", ")", "return", "command", ",", "args" ]
Split command and args :return: tuple of (command, args)
[ "Split", "command", "and", "args" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L156-L164
train
219,553
aiogram/aiogram
aiogram/types/message.py
Message.get_command
def get_command(self, pure=False): """ Get command from message :return: """ command = self.get_full_command() if command: command = command[0] if pure: command, _, _ = command[1:].partition('@') return command
python
def get_command(self, pure=False): """ Get command from message :return: """ command = self.get_full_command() if command: command = command[0] if pure: command, _, _ = command[1:].partition('@') return command
[ "def", "get_command", "(", "self", ",", "pure", "=", "False", ")", ":", "command", "=", "self", ".", "get_full_command", "(", ")", "if", "command", ":", "command", "=", "command", "[", "0", "]", "if", "pure", ":", "command", ",", "_", ",", "_", "="...
Get command from message :return:
[ "Get", "command", "from", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L166-L177
train
219,554
aiogram/aiogram
aiogram/types/message.py
Message.parse_entities
def parse_entities(self, as_html=True): """ Text or caption formatted as HTML or Markdown. :return: str """ text = self.text or self.caption if text is None: raise TypeError("This message doesn't have any text.") quote_fn = md.quote_html if as_html else md.escape_md entities = self.entities or self.caption_entities if not entities: return quote_fn(text) if not sys.maxunicode == 0xffff: text = text.encode('utf-16-le') result = '' offset = 0 for entity in sorted(entities, key=lambda item: item.offset): entity_text = entity.parse(text, as_html=as_html) if sys.maxunicode == 0xffff: part = text[offset:entity.offset] result += quote_fn(part) + entity_text else: part = text[offset * 2:entity.offset * 2] result += quote_fn(part.decode('utf-16-le')) + entity_text offset = entity.offset + entity.length if sys.maxunicode == 0xffff: part = text[offset:] result += quote_fn(part) else: part = text[offset * 2:] result += quote_fn(part.decode('utf-16-le')) return result
python
def parse_entities(self, as_html=True): """ Text or caption formatted as HTML or Markdown. :return: str """ text = self.text or self.caption if text is None: raise TypeError("This message doesn't have any text.") quote_fn = md.quote_html if as_html else md.escape_md entities = self.entities or self.caption_entities if not entities: return quote_fn(text) if not sys.maxunicode == 0xffff: text = text.encode('utf-16-le') result = '' offset = 0 for entity in sorted(entities, key=lambda item: item.offset): entity_text = entity.parse(text, as_html=as_html) if sys.maxunicode == 0xffff: part = text[offset:entity.offset] result += quote_fn(part) + entity_text else: part = text[offset * 2:entity.offset * 2] result += quote_fn(part.decode('utf-16-le')) + entity_text offset = entity.offset + entity.length if sys.maxunicode == 0xffff: part = text[offset:] result += quote_fn(part) else: part = text[offset * 2:] result += quote_fn(part.decode('utf-16-le')) return result
[ "def", "parse_entities", "(", "self", ",", "as_html", "=", "True", ")", ":", "text", "=", "self", ".", "text", "or", "self", ".", "caption", "if", "text", "is", "None", ":", "raise", "TypeError", "(", "\"This message doesn't have any text.\"", ")", "quote_fn...
Text or caption formatted as HTML or Markdown. :return: str
[ "Text", "or", "caption", "formatted", "as", "HTML", "or", "Markdown", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L189-L231
train
219,555
aiogram/aiogram
aiogram/types/message.py
Message.url
def url(self) -> str: """ Get URL for the message :return: str """ if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]: raise TypeError('Invalid chat type!') elif not self.chat.username: raise TypeError('This chat does not have @username') return f"https://t.me/{self.chat.username}/{self.message_id}"
python
def url(self) -> str: """ Get URL for the message :return: str """ if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]: raise TypeError('Invalid chat type!') elif not self.chat.username: raise TypeError('This chat does not have @username') return f"https://t.me/{self.chat.username}/{self.message_id}"
[ "def", "url", "(", "self", ")", "->", "str", ":", "if", "self", ".", "chat", ".", "type", "not", "in", "[", "ChatType", ".", "SUPER_GROUP", ",", "ChatType", ".", "CHANNEL", "]", ":", "raise", "TypeError", "(", "'Invalid chat type!'", ")", "elif", "not"...
Get URL for the message :return: str
[ "Get", "URL", "for", "the", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L252-L263
train
219,556
aiogram/aiogram
aiogram/types/message.py
Message.link
def link(self, text, as_html=True) -> str: """ Generate URL for using in text messages with HTML or MD parse mode :param text: link label :param as_html: generate as HTML :return: str """ try: url = self.url except TypeError: # URL is not accessible if as_html: return md.quote_html(text) return md.escape_md(text) if as_html: return md.hlink(text, url) return md.link(text, url)
python
def link(self, text, as_html=True) -> str: """ Generate URL for using in text messages with HTML or MD parse mode :param text: link label :param as_html: generate as HTML :return: str """ try: url = self.url except TypeError: # URL is not accessible if as_html: return md.quote_html(text) return md.escape_md(text) if as_html: return md.hlink(text, url) return md.link(text, url)
[ "def", "link", "(", "self", ",", "text", ",", "as_html", "=", "True", ")", "->", "str", ":", "try", ":", "url", "=", "self", ".", "url", "except", "TypeError", ":", "# URL is not accessible", "if", "as_html", ":", "return", "md", ".", "quote_html", "("...
Generate URL for using in text messages with HTML or MD parse mode :param text: link label :param as_html: generate as HTML :return: str
[ "Generate", "URL", "for", "using", "in", "text", "messages", "with", "HTML", "or", "MD", "parse", "mode" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L265-L282
train
219,557
aiogram/aiogram
aiogram/types/message.py
Message.answer
async def answer(self, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_markup=None, reply=False) -> Message: """ Answer to this message :param text: str :param parse_mode: str :param disable_web_page_preview: bool :param disable_notification: bool :param reply_markup: :param reply: fill 'reply_to_message_id' :return: :class:`aiogram.types.Message` """ return await self.bot.send_message(chat_id=self.chat.id, text=text, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
python
async def answer(self, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_markup=None, reply=False) -> Message: """ Answer to this message :param text: str :param parse_mode: str :param disable_web_page_preview: bool :param disable_notification: bool :param reply_markup: :param reply: fill 'reply_to_message_id' :return: :class:`aiogram.types.Message` """ return await self.bot.send_message(chat_id=self.chat.id, text=text, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
[ "async", "def", "answer", "(", "self", ",", "text", ",", "parse_mode", "=", "None", ",", "disable_web_page_preview", "=", "None", ",", "disable_notification", "=", "None", ",", "reply_markup", "=", "None", ",", "reply", "=", "False", ")", "->", "Message", ...
Answer to this message :param text: str :param parse_mode: str :param disable_web_page_preview: bool :param disable_notification: bool :param reply_markup: :param reply: fill 'reply_to_message_id' :return: :class:`aiogram.types.Message`
[ "Answer", "to", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L284-L302
train
219,558
aiogram/aiogram
aiogram/types/message.py
Message.answer_photo
async def answer_photo(self, photo: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_markup=None, reply=False) -> Message: """ Use this method to send photos. Source: https://core.telegram.org/bots/api#sendphoto :param photo: Photo to send. :type photo: :obj:`typing.Union[base.InputFile, base.String]` :param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters :type caption: :obj:`typing.Union[base.String, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_markup: Additional interface options. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :param reply: fill 'reply_to_message_id' :return: On success, the sent Message is returned. :rtype: :obj:`types.Message` """ return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
python
async def answer_photo(self, photo: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_markup=None, reply=False) -> Message: """ Use this method to send photos. Source: https://core.telegram.org/bots/api#sendphoto :param photo: Photo to send. :type photo: :obj:`typing.Union[base.InputFile, base.String]` :param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters :type caption: :obj:`typing.Union[base.String, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_markup: Additional interface options. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :param reply: fill 'reply_to_message_id' :return: On success, the sent Message is returned. :rtype: :obj:`types.Message` """ return await self.bot.send_photo(chat_id=self.chat.id, photo=photo, caption=caption, disable_notification=disable_notification, reply_to_message_id=self.message_id if reply else None, reply_markup=reply_markup)
[ "async", "def", "answer_photo", "(", "self", ",", "photo", ":", "typing", ".", "Union", "[", "base", ".", "InputFile", ",", "base", ".", "String", "]", ",", "caption", ":", "typing", ".", "Union", "[", "base", ".", "String", ",", "None", "]", "=", ...
Use this method to send photos. Source: https://core.telegram.org/bots/api#sendphoto :param photo: Photo to send. :type photo: :obj:`typing.Union[base.InputFile, base.String]` :param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters :type caption: :obj:`typing.Union[base.String, None]` :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: :obj:`typing.Union[base.Boolean, None]` :param reply_markup: Additional interface options. :type reply_markup: :obj:`typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, None]` :param reply: fill 'reply_to_message_id' :return: On success, the sent Message is returned. :rtype: :obj:`types.Message`
[ "Use", "this", "method", "to", "send", "photos", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L304-L329
train
219,559
aiogram/aiogram
aiogram/types/message.py
Message.forward
async def forward(self, chat_id, disable_notification=None) -> Message: """ Forward this message :param chat_id: :param disable_notification: :return: """ return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification)
python
async def forward(self, chat_id, disable_notification=None) -> Message: """ Forward this message :param chat_id: :param disable_notification: :return: """ return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification)
[ "async", "def", "forward", "(", "self", ",", "chat_id", ",", "disable_notification", "=", "None", ")", "->", "Message", ":", "return", "await", "self", ".", "bot", ".", "forward_message", "(", "chat_id", ",", "self", ".", "chat", ".", "id", ",", "self", ...
Forward this message :param chat_id: :param disable_notification: :return:
[ "Forward", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1322-L1330
train
219,560
aiogram/aiogram
aiogram/types/message.py
Message.delete
async def delete(self): """ Delete this message :return: bool """ return await self.bot.delete_message(self.chat.id, self.message_id)
python
async def delete(self): """ Delete this message :return: bool """ return await self.bot.delete_message(self.chat.id, self.message_id)
[ "async", "def", "delete", "(", "self", ")", ":", "return", "await", "self", ".", "bot", ".", "delete_message", "(", "self", ".", "chat", ".", "id", ",", "self", ".", "message_id", ")" ]
Delete this message :return: bool
[ "Delete", "this", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1470-L1476
train
219,561
aiogram/aiogram
aiogram/utils/callback_data.py
CallbackData.new
def new(self, *args, **kwargs) -> str: """ Generate callback data :param args: :param kwargs: :return: """ args = list(args) data = [self.prefix] for part in self._part_names: value = kwargs.pop(part, None) if value is None: if args: value = args.pop(0) else: raise ValueError(f"Value for '{part}' is not passed!") if value is not None and not isinstance(value, str): value = str(value) if not value: raise ValueError(f"Value for part {part} can't be empty!'") elif self.sep in value: raise ValueError(f"Symbol defined as separator can't be used in values of parts") data.append(value) if args or kwargs: raise TypeError('Too many arguments is passed!') callback_data = self.sep.join(data) if len(callback_data) > 64: raise ValueError('Resulted callback data is too long!') return callback_data
python
def new(self, *args, **kwargs) -> str: """ Generate callback data :param args: :param kwargs: :return: """ args = list(args) data = [self.prefix] for part in self._part_names: value = kwargs.pop(part, None) if value is None: if args: value = args.pop(0) else: raise ValueError(f"Value for '{part}' is not passed!") if value is not None and not isinstance(value, str): value = str(value) if not value: raise ValueError(f"Value for part {part} can't be empty!'") elif self.sep in value: raise ValueError(f"Symbol defined as separator can't be used in values of parts") data.append(value) if args or kwargs: raise TypeError('Too many arguments is passed!') callback_data = self.sep.join(data) if len(callback_data) > 64: raise ValueError('Resulted callback data is too long!') return callback_data
[ "def", "new", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "str", ":", "args", "=", "list", "(", "args", ")", "data", "=", "[", "self", ".", "prefix", "]", "for", "part", "in", "self", ".", "_part_names", ":", "value", "="...
Generate callback data :param args: :param kwargs: :return:
[ "Generate", "callback", "data" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/callback_data.py#L44-L81
train
219,562
aiogram/aiogram
examples/webhook_example.py
cmd_id
async def cmd_id(message: types.Message): """ Return info about user. """ if message.reply_to_message: target = message.reply_to_message.from_user chat = message.chat elif message.forward_from and message.chat.type == ChatType.PRIVATE: target = message.forward_from chat = message.forward_from or message.chat else: target = message.from_user chat = message.chat result_msg = [hbold('Info about user:'), f"First name: {target.first_name}"] if target.last_name: result_msg.append(f"Last name: {target.last_name}") if target.username: result_msg.append(f"Username: {target.mention}") result_msg.append(f"User ID: {target.id}") result_msg.extend([hbold('Chat:'), f"Type: {chat.type}", f"Chat ID: {chat.id}"]) if chat.type != ChatType.PRIVATE: result_msg.append(f"Title: {chat.title}") else: result_msg.append(f"Title: {chat.full_name}") return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML)
python
async def cmd_id(message: types.Message): """ Return info about user. """ if message.reply_to_message: target = message.reply_to_message.from_user chat = message.chat elif message.forward_from and message.chat.type == ChatType.PRIVATE: target = message.forward_from chat = message.forward_from or message.chat else: target = message.from_user chat = message.chat result_msg = [hbold('Info about user:'), f"First name: {target.first_name}"] if target.last_name: result_msg.append(f"Last name: {target.last_name}") if target.username: result_msg.append(f"Username: {target.mention}") result_msg.append(f"User ID: {target.id}") result_msg.extend([hbold('Chat:'), f"Type: {chat.type}", f"Chat ID: {chat.id}"]) if chat.type != ChatType.PRIVATE: result_msg.append(f"Title: {chat.title}") else: result_msg.append(f"Title: {chat.full_name}") return SendMessage(message.chat.id, '\n'.join(result_msg), reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML)
[ "async", "def", "cmd_id", "(", "message", ":", "types", ".", "Message", ")", ":", "if", "message", ".", "reply_to_message", ":", "target", "=", "message", ".", "reply_to_message", ".", "from_user", "chat", "=", "message", ".", "chat", "elif", "message", "....
Return info about user.
[ "Return", "info", "about", "user", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L83-L113
train
219,563
aiogram/aiogram
examples/webhook_example.py
on_shutdown
async def on_shutdown(app): """ Graceful shutdown. This method is recommended by aiohttp docs. """ # Remove webhook. await bot.delete_webhook() # Close Redis connection. await dp.storage.close() await dp.storage.wait_closed()
python
async def on_shutdown(app): """ Graceful shutdown. This method is recommended by aiohttp docs. """ # Remove webhook. await bot.delete_webhook() # Close Redis connection. await dp.storage.close() await dp.storage.wait_closed()
[ "async", "def", "on_shutdown", "(", "app", ")", ":", "# Remove webhook.", "await", "bot", ".", "delete_webhook", "(", ")", "# Close Redis connection.", "await", "dp", ".", "storage", ".", "close", "(", ")", "await", "dp", ".", "storage", ".", "wait_closed", ...
Graceful shutdown. This method is recommended by aiohttp docs.
[ "Graceful", "shutdown", ".", "This", "method", "is", "recommended", "by", "aiohttp", "docs", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L149-L158
train
219,564
aiogram/aiogram
aiogram/types/input_file.py
InputFile.from_url
def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE): """ Download file from URL Manually is not required action. You can send urls instead! :param url: target URL :param filename: optional. set custom file name :param chunk_size: :return: InputFile """ pipe = _WebPipe(url, chunk_size=chunk_size) if filename is None: filename = pipe.name return cls(pipe, filename, chunk_size)
python
def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE): """ Download file from URL Manually is not required action. You can send urls instead! :param url: target URL :param filename: optional. set custom file name :param chunk_size: :return: InputFile """ pipe = _WebPipe(url, chunk_size=chunk_size) if filename is None: filename = pipe.name return cls(pipe, filename, chunk_size)
[ "def", "from_url", "(", "cls", ",", "url", ",", "filename", "=", "None", ",", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "pipe", "=", "_WebPipe", "(", "url", ",", "chunk_size", "=", "chunk_size", ")", "if", "filename", "is", "None", ":", "filename", "=...
Download file from URL Manually is not required action. You can send urls instead! :param url: target URL :param filename: optional. set custom file name :param chunk_size: :return: InputFile
[ "Download", "file", "from", "URL" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L101-L117
train
219,565
aiogram/aiogram
aiogram/types/input_file.py
InputFile.save
def save(self, filename, chunk_size=CHUNK_SIZE): """ Write file to disk :param filename: :param chunk_size: """ with open(filename, 'wb') as fp: while True: # Chunk writer data = self.file.read(chunk_size) if not data: break fp.write(data) # Flush all data fp.flush() # Go to start of file. if self.file.seekable(): self.file.seek(0)
python
def save(self, filename, chunk_size=CHUNK_SIZE): """ Write file to disk :param filename: :param chunk_size: """ with open(filename, 'wb') as fp: while True: # Chunk writer data = self.file.read(chunk_size) if not data: break fp.write(data) # Flush all data fp.flush() # Go to start of file. if self.file.seekable(): self.file.seek(0)
[ "def", "save", "(", "self", ",", "filename", ",", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "fp", ":", "while", "True", ":", "# Chunk writer", "data", "=", "self", ".", "file", ".", "read", "(...
Write file to disk :param filename: :param chunk_size:
[ "Write", "file", "to", "disk" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L119-L138
train
219,566
aiogram/aiogram
aiogram/types/force_reply.py
ForceReply.create
def create(cls, selective: typing.Optional[base.Boolean] = None): """ Create new force reply :param selective: :return: """ return cls(selective=selective)
python
def create(cls, selective: typing.Optional[base.Boolean] = None): """ Create new force reply :param selective: :return: """ return cls(selective=selective)
[ "def", "create", "(", "cls", ",", "selective", ":", "typing", ".", "Optional", "[", "base", ".", "Boolean", "]", "=", "None", ")", ":", "return", "cls", "(", "selective", "=", "selective", ")" ]
Create new force reply :param selective: :return:
[ "Create", "new", "force", "reply" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/force_reply.py#L29-L36
train
219,567
aiogram/aiogram
examples/finite_state_machine_example.py
cancel_handler
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None): """ Allow user to cancel any action """ if raw_state is None: return # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove())
python
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None): """ Allow user to cancel any action """ if raw_state is None: return # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await message.reply('Canceled.', reply_markup=types.ReplyKeyboardRemove())
[ "async", "def", "cancel_handler", "(", "message", ":", "types", ".", "Message", ",", "state", ":", "FSMContext", ",", "raw_state", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "raw_state", "is", "None", ":", "return", "# Cancel state and ...
Allow user to cancel any action
[ "Allow", "user", "to", "cancel", "any", "action" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L44-L54
train
219,568
aiogram/aiogram
examples/finite_state_machine_example.py
process_name
async def process_name(message: types.Message, state: FSMContext): """ Process user name """ async with state.proxy() as data: data['name'] = message.text await Form.next() await message.reply("How old are you?")
python
async def process_name(message: types.Message, state: FSMContext): """ Process user name """ async with state.proxy() as data: data['name'] = message.text await Form.next() await message.reply("How old are you?")
[ "async", "def", "process_name", "(", "message", ":", "types", ".", "Message", ",", "state", ":", "FSMContext", ")", ":", "async", "with", "state", ".", "proxy", "(", ")", "as", "data", ":", "data", "[", "'name'", "]", "=", "message", ".", "text", "aw...
Process user name
[ "Process", "user", "name" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L58-L66
train
219,569
aiogram/aiogram
examples/middleware_and_antiflood.py
rate_limit
def rate_limit(limit: int, key=None): """ Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return: """ def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) return func return decorator
python
def rate_limit(limit: int, key=None): """ Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return: """ def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) return func return decorator
[ "def", "rate_limit", "(", "limit", ":", "int", ",", "key", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "setattr", "(", "func", ",", "'throttling_rate_limit'", ",", "limit", ")", "if", "key", ":", "setattr", "(", "func", ",", "'t...
Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return:
[ "Decorator", "for", "configuring", "rate", "limit", "and", "key", "in", "different", "functions", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L21-L36
train
219,570
aiogram/aiogram
examples/middleware_and_antiflood.py
ThrottlingMiddleware.on_process_message
async def on_process_message(self, message: types.Message, data: dict): """ This handler is called when dispatcher receives a message :param message: """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
python
async def on_process_message(self, message: types.Message, data: dict): """ This handler is called when dispatcher receives a message :param message: """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
[ "async", "def", "on_process_message", "(", "self", ",", "message", ":", "types", ".", "Message", ",", "data", ":", "dict", ")", ":", "# Get current handler", "handler", "=", "current_handler", ".", "get", "(", ")", "# Get dispatcher from context", "dispatcher", ...
This handler is called when dispatcher receives a message :param message:
[ "This", "handler", "is", "called", "when", "dispatcher", "receives", "a", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L49-L76
train
219,571
aiogram/aiogram
examples/middleware_and_antiflood.py
ThrottlingMiddleware.message_throttled
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
python
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
[ "async", "def", "message_throttled", "(", "self", ",", "message", ":", "types", ".", "Message", ",", "throttled", ":", "Throttled", ")", ":", "handler", "=", "current_handler", ".", "get", "(", ")", "dispatcher", "=", "Dispatcher", ".", "get_current", "(", ...
Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled:
[ "Notify", "user", "only", "on", "first", "exceed", "and", "notify", "about", "unlocking", "only", "on", "last", "exceed" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L78-L107
train
219,572
aiogram/aiogram
aiogram/utils/auth_widget.py
generate_hash
def generate_hash(data: dict, token: str) -> str: """ Generate secret hash :param data: :param token: :return: """ secret = hashlib.sha256() secret.update(token.encode('utf-8')) sorted_params = collections.OrderedDict(sorted(data.items())) msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash') return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
python
def generate_hash(data: dict, token: str) -> str: """ Generate secret hash :param data: :param token: :return: """ secret = hashlib.sha256() secret.update(token.encode('utf-8')) sorted_params = collections.OrderedDict(sorted(data.items())) msg = '\n'.join("{}={}".format(k, v) for k, v in sorted_params.items() if k != 'hash') return hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
[ "def", "generate_hash", "(", "data", ":", "dict", ",", "token", ":", "str", ")", "->", "str", ":", "secret", "=", "hashlib", ".", "sha256", "(", ")", "secret", ".", "update", "(", "token", ".", "encode", "(", "'utf-8'", ")", ")", "sorted_params", "="...
Generate secret hash :param data: :param token: :return:
[ "Generate", "secret", "hash" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L12-L24
train
219,573
aiogram/aiogram
aiogram/utils/auth_widget.py
check_token
def check_token(data: dict, token: str) -> bool: """ Validate auth token :param data: :param token: :return: """ param_hash = data.get('hash', '') or '' return param_hash == generate_hash(data, token)
python
def check_token(data: dict, token: str) -> bool: """ Validate auth token :param data: :param token: :return: """ param_hash = data.get('hash', '') or '' return param_hash == generate_hash(data, token)
[ "def", "check_token", "(", "data", ":", "dict", ",", "token", ":", "str", ")", "->", "bool", ":", "param_hash", "=", "data", ".", "get", "(", "'hash'", ",", "''", ")", "or", "''", "return", "param_hash", "==", "generate_hash", "(", "data", ",", "toke...
Validate auth token :param data: :param token: :return:
[ "Validate", "auth", "token" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L27-L36
train
219,574
aiogram/aiogram
aiogram/dispatcher/filters/factory.py
FiltersFactory.resolve
def resolve(self, event_handler, *custom_filters, **full_config ) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]: """ Resolve filters to filters-set :param event_handler: :param custom_filters: :param full_config: :return: """ filters_set = [] filters_set.extend(self._resolve_registered(event_handler, {k: v for k, v in full_config.items() if v is not None})) if custom_filters: filters_set.extend(custom_filters) return filters_set
python
def resolve(self, event_handler, *custom_filters, **full_config ) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]: """ Resolve filters to filters-set :param event_handler: :param custom_filters: :param full_config: :return: """ filters_set = [] filters_set.extend(self._resolve_registered(event_handler, {k: v for k, v in full_config.items() if v is not None})) if custom_filters: filters_set.extend(custom_filters) return filters_set
[ "def", "resolve", "(", "self", ",", "event_handler", ",", "*", "custom_filters", ",", "*", "*", "full_config", ")", "->", "typing", ".", "List", "[", "typing", ".", "Union", "[", "typing", ".", "Callable", ",", "AbstractFilter", "]", "]", ":", "filters_s...
Resolve filters to filters-set :param event_handler: :param custom_filters: :param full_config: :return:
[ "Resolve", "filters", "to", "filters", "-", "set" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L41-L57
train
219,575
aiogram/aiogram
aiogram/dispatcher/filters/factory.py
FiltersFactory._resolve_registered
def _resolve_registered(self, event_handler, full_config) -> typing.Generator: """ Resolve registered filters :param event_handler: :param full_config: :return: """ for record in self._registered: filter_ = record.resolve(self._dispatcher, event_handler, full_config) if filter_: yield filter_ if full_config: raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'')
python
def _resolve_registered(self, event_handler, full_config) -> typing.Generator: """ Resolve registered filters :param event_handler: :param full_config: :return: """ for record in self._registered: filter_ = record.resolve(self._dispatcher, event_handler, full_config) if filter_: yield filter_ if full_config: raise NameError('Invalid filter name(s): \'' + '\', '.join(full_config.keys()) + '\'')
[ "def", "_resolve_registered", "(", "self", ",", "event_handler", ",", "full_config", ")", "->", "typing", ".", "Generator", ":", "for", "record", "in", "self", ".", "_registered", ":", "filter_", "=", "record", ".", "resolve", "(", "self", ".", "_dispatcher"...
Resolve registered filters :param event_handler: :param full_config: :return:
[ "Resolve", "registered", "filters" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L59-L73
train
219,576
aiogram/aiogram
aiogram/types/auth_widget_data.py
AuthWidgetData.parse
def parse(cls, request: web.Request) -> AuthWidgetData: """ Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest` """ try: query = dict(request.query) query['id'] = int(query['id']) query['auth_date'] = int(query['auth_date']) widget = AuthWidgetData(**query) except (ValueError, KeyError): raise web.HTTPBadRequest(text='Invalid auth data') else: return widget
python
def parse(cls, request: web.Request) -> AuthWidgetData: """ Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest` """ try: query = dict(request.query) query['id'] = int(query['id']) query['auth_date'] = int(query['auth_date']) widget = AuthWidgetData(**query) except (ValueError, KeyError): raise web.HTTPBadRequest(text='Invalid auth data') else: return widget
[ "def", "parse", "(", "cls", ",", "request", ":", "web", ".", "Request", ")", "->", "AuthWidgetData", ":", "try", ":", "query", "=", "dict", "(", "request", ".", "query", ")", "query", "[", "'id'", "]", "=", "int", "(", "query", "[", "'id'", "]", ...
Parse request as Telegram auth widget data. :param request: :return: :obj:`AuthWidgetData` :raise: :obj:`aiohttp.web.HTTPBadRequest`
[ "Parse", "request", "as", "Telegram", "auth", "widget", "data", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/auth_widget_data.py#L19-L35
train
219,577
aiogram/aiogram
aiogram/dispatcher/webhook.py
_check_ip
def _check_ip(ip: str) -> bool: """ Check IP in range :param ip: :return: """ address = ipaddress.IPv4Address(ip) return address in allowed_ips
python
def _check_ip(ip: str) -> bool: """ Check IP in range :param ip: :return: """ address = ipaddress.IPv4Address(ip) return address in allowed_ips
[ "def", "_check_ip", "(", "ip", ":", "str", ")", "->", "bool", ":", "address", "=", "ipaddress", ".", "IPv4Address", "(", "ip", ")", "return", "address", "in", "allowed_ips" ]
Check IP in range :param ip: :return:
[ "Check", "IP", "in", "range" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L39-L47
train
219,578
aiogram/aiogram
aiogram/dispatcher/webhook.py
allow_ip
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]): """ Allow ip address. :param ips: :return: """ for ip in ips: if isinstance(ip, ipaddress.IPv4Address): allowed_ips.add(ip) elif isinstance(ip, str): allowed_ips.add(ipaddress.IPv4Address(ip)) elif isinstance(ip, ipaddress.IPv4Network): allowed_ips.update(ip.hosts()) else: raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
python
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]): """ Allow ip address. :param ips: :return: """ for ip in ips: if isinstance(ip, ipaddress.IPv4Address): allowed_ips.add(ip) elif isinstance(ip, str): allowed_ips.add(ipaddress.IPv4Address(ip)) elif isinstance(ip, ipaddress.IPv4Network): allowed_ips.update(ip.hosts()) else: raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
[ "def", "allow_ip", "(", "*", "ips", ":", "typing", ".", "Union", "[", "str", ",", "ipaddress", ".", "IPv4Network", ",", "ipaddress", ".", "IPv4Address", "]", ")", ":", "for", "ip", "in", "ips", ":", "if", "isinstance", "(", "ip", ",", "ipaddress", "....
Allow ip address. :param ips: :return:
[ "Allow", "ip", "address", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L50-L65
train
219,579
aiogram/aiogram
aiogram/dispatcher/webhook.py
configure_app
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME): """ You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :param route_name: Name of webhook handler route :return: """ app.router.add_route('*', path, WebhookRequestHandler, name=route_name) app[BOT_DISPATCHER_KEY] = dispatcher
python
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME): """ You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :param route_name: Name of webhook handler route :return: """ app.router.add_route('*', path, WebhookRequestHandler, name=route_name) app[BOT_DISPATCHER_KEY] = dispatcher
[ "def", "configure_app", "(", "dispatcher", ",", "app", ":", "web", ".", "Application", ",", "path", "=", "DEFAULT_WEB_PATH", ",", "route_name", "=", "DEFAULT_ROUTE_NAME", ")", ":", "app", ".", "router", ".", "add_route", "(", "'*'", ",", "path", ",", "Webh...
You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :param route_name: Name of webhook handler route :return:
[ "You", "can", "prepare", "web", ".", "Application", "for", "working", "with", "webhook", "handler", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L278-L289
train
219,580
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.get_dispatcher
def get_dispatcher(self): """ Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher` """ dp = self.request.app[BOT_DISPATCHER_KEY] try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dp) Bot.set_current(dp.bot) except RuntimeError: pass return dp
python
def get_dispatcher(self): """ Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher` """ dp = self.request.app[BOT_DISPATCHER_KEY] try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dp) Bot.set_current(dp.bot) except RuntimeError: pass return dp
[ "def", "get_dispatcher", "(", "self", ")", ":", "dp", "=", "self", ".", "request", ".", "app", "[", "BOT_DISPATCHER_KEY", "]", "try", ":", "from", "aiogram", "import", "Bot", ",", "Dispatcher", "Dispatcher", ".", "set_current", "(", "dp", ")", "Bot", "."...
Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher`
[ "Get", "Dispatcher", "instance", "from", "environment" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L93-L106
train
219,581
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.parse_update
async def parse_update(self, bot): """ Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update` """ data = await self.request.json() update = types.Update(**data) return update
python
async def parse_update(self, bot): """ Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update` """ data = await self.request.json() update = types.Update(**data) return update
[ "async", "def", "parse_update", "(", "self", ",", "bot", ")", ":", "data", "=", "await", "self", ".", "request", ".", "json", "(", ")", "update", "=", "types", ".", "Update", "(", "*", "*", "data", ")", "return", "update" ]
Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update`
[ "Read", "update", "from", "stream", "and", "deserialize", "it", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L108-L117
train
219,582
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.post
async def post(self): """ Process POST request if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook. Otherwise do nothing (return 'ok') :return: :class:`aiohttp.web.Response` """ self.validate_ip() # context.update_state({'CALLER': WEBHOOK, # WEBHOOK_CONNECTION: True, # WEBHOOK_REQUEST: self.request}) dispatcher = self.get_dispatcher() update = await self.parse_update(dispatcher.bot) results = await self.process_update(update) response = self.get_response(results) if response: web_response = response.get_web_response() else: web_response = web.Response(text='ok') if self.request.app.get('RETRY_AFTER', None): web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER'] return web_response
python
async def post(self): """ Process POST request if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook. Otherwise do nothing (return 'ok') :return: :class:`aiohttp.web.Response` """ self.validate_ip() # context.update_state({'CALLER': WEBHOOK, # WEBHOOK_CONNECTION: True, # WEBHOOK_REQUEST: self.request}) dispatcher = self.get_dispatcher() update = await self.parse_update(dispatcher.bot) results = await self.process_update(update) response = self.get_response(results) if response: web_response = response.get_web_response() else: web_response = web.Response(text='ok') if self.request.app.get('RETRY_AFTER', None): web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER'] return web_response
[ "async", "def", "post", "(", "self", ")", ":", "self", ".", "validate_ip", "(", ")", "# context.update_state({'CALLER': WEBHOOK,", "# WEBHOOK_CONNECTION: True,", "# WEBHOOK_REQUEST: self.request})", "dispatcher", "=", "self", ".", "ge...
Process POST request if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook. Otherwise do nothing (return 'ok') :return: :class:`aiohttp.web.Response`
[ "Process", "POST", "request" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L119-L148
train
219,583
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.process_update
async def process_update(self, update): """ Need respond in less than 60 seconds in to webhook. So... If you respond greater than 55 seconds webhook automatically respond 'ok' and execute callback response via simple HTTP request. :param update: :return: """ dispatcher = self.get_dispatcher() loop = dispatcher.loop # Analog of `asyncio.wait_for` but without cancelling task waiter = loop.create_future() timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter) cb = functools.partial(asyncio.tasks._release_waiter, waiter) fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop) fut.add_done_callback(cb) try: try: await waiter except asyncio.futures.CancelledError: fut.remove_done_callback(cb) fut.cancel() raise if fut.done(): return fut.result() else: # context.set_value(WEBHOOK_CONNECTION, False) fut.remove_done_callback(cb) fut.add_done_callback(self.respond_via_request) finally: timeout_handle.cancel()
python
async def process_update(self, update): """ Need respond in less than 60 seconds in to webhook. So... If you respond greater than 55 seconds webhook automatically respond 'ok' and execute callback response via simple HTTP request. :param update: :return: """ dispatcher = self.get_dispatcher() loop = dispatcher.loop # Analog of `asyncio.wait_for` but without cancelling task waiter = loop.create_future() timeout_handle = loop.call_later(RESPONSE_TIMEOUT, asyncio.tasks._release_waiter, waiter) cb = functools.partial(asyncio.tasks._release_waiter, waiter) fut = asyncio.ensure_future(dispatcher.updates_handler.notify(update), loop=loop) fut.add_done_callback(cb) try: try: await waiter except asyncio.futures.CancelledError: fut.remove_done_callback(cb) fut.cancel() raise if fut.done(): return fut.result() else: # context.set_value(WEBHOOK_CONNECTION, False) fut.remove_done_callback(cb) fut.add_done_callback(self.respond_via_request) finally: timeout_handle.cancel()
[ "async", "def", "process_update", "(", "self", ",", "update", ")", ":", "dispatcher", "=", "self", ".", "get_dispatcher", "(", ")", "loop", "=", "dispatcher", ".", "loop", "# Analog of `asyncio.wait_for` but without cancelling task", "waiter", "=", "loop", ".", "c...
Need respond in less than 60 seconds in to webhook. So... If you respond greater than 55 seconds webhook automatically respond 'ok' and execute callback response via simple HTTP request. :param update: :return:
[ "Need", "respond", "in", "less", "than", "60", "seconds", "in", "to", "webhook", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L158-L194
train
219,584
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.respond_via_request
def respond_via_request(self, task): """ Handle response after 55 second. :param task: :return: """ warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.", TimeoutWarning) dispatcher = self.get_dispatcher() loop = dispatcher.loop try: results = task.result() except Exception as e: loop.create_task( dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e)) else: response = self.get_response(results) if response is not None: asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
python
def respond_via_request(self, task): """ Handle response after 55 second. :param task: :return: """ warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.", TimeoutWarning) dispatcher = self.get_dispatcher() loop = dispatcher.loop try: results = task.result() except Exception as e: loop.create_task( dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e)) else: response = self.get_response(results) if response is not None: asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
[ "def", "respond_via_request", "(", "self", ",", "task", ")", ":", "warn", "(", "f\"Detected slow response into webhook. \"", "f\"(Greater than {RESPONSE_TIMEOUT} seconds)\\n\"", "f\"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.\"", ",", "Timeou...
Handle response after 55 second. :param task: :return:
[ "Handle", "response", "after", "55", "second", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L196-L219
train
219,585
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.get_response
def get_response(self, results): """ Get response object from results. :param results: list :return: """ if results is None: return None for result in itertools.chain.from_iterable(results): if isinstance(result, BaseResponse): return result
python
def get_response(self, results): """ Get response object from results. :param results: list :return: """ if results is None: return None for result in itertools.chain.from_iterable(results): if isinstance(result, BaseResponse): return result
[ "def", "get_response", "(", "self", ",", "results", ")", ":", "if", "results", "is", "None", ":", "return", "None", "for", "result", "in", "itertools", ".", "chain", ".", "from_iterable", "(", "results", ")", ":", "if", "isinstance", "(", "result", ",", ...
Get response object from results. :param results: list :return:
[ "Get", "response", "object", "from", "results", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L221-L232
train
219,586
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.check_ip
def check_ip(self): """ Check client IP. Accept requests only from telegram servers. :return: """ # For reverse proxy (nginx) forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) # For default method peer_name = self.request.transport.get_extra_info('peername') if peer_name is not None: host, _ = peer_name return host, _check_ip(host) # Not allowed and can't get client IP return None, False
python
def check_ip(self): """ Check client IP. Accept requests only from telegram servers. :return: """ # For reverse proxy (nginx) forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) # For default method peer_name = self.request.transport.get_extra_info('peername') if peer_name is not None: host, _ = peer_name return host, _check_ip(host) # Not allowed and can't get client IP return None, False
[ "def", "check_ip", "(", "self", ")", ":", "# For reverse proxy (nginx)", "forwarded_for", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'X-Forwarded-For'", ",", "None", ")", "if", "forwarded_for", ":", "return", "forwarded_for", ",", "_check_ip"...
Check client IP. Accept requests only from telegram servers. :return:
[ "Check", "client", "IP", ".", "Accept", "requests", "only", "from", "telegram", "servers", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L234-L252
train
219,587
aiogram/aiogram
aiogram/dispatcher/webhook.py
WebhookRequestHandler.validate_ip
def validate_ip(self): """ Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. """ if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
python
def validate_ip(self): """ Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. """ if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
[ "def", "validate_ip", "(", "self", ")", ":", "if", "self", ".", "request", ".", "app", ".", "get", "(", "'_check_ip'", ",", "False", ")", ":", "ip_address", ",", "accept", "=", "self", ".", "check_ip", "(", ")", "if", "not", "accept", ":", "raise", ...
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
[ "Check", "ip", "if", "that", "is", "needed", ".", "Raise", "web", ".", "HTTPUnauthorized", "for", "not", "allowed", "hosts", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L254-L261
train
219,588
aiogram/aiogram
aiogram/dispatcher/webhook.py
BaseResponse.cleanup
def cleanup(self) -> typing.Dict: """ Cleanup response after preparing. Remove empty fields. :return: response parameters dict """ return {k: v for k, v in self.prepare().items() if v is not None}
python
def cleanup(self) -> typing.Dict: """ Cleanup response after preparing. Remove empty fields. :return: response parameters dict """ return {k: v for k, v in self.prepare().items() if v is not None}
[ "def", "cleanup", "(", "self", ")", "->", "typing", ".", "Dict", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "prepare", "(", ")", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}" ]
Cleanup response after preparing. Remove empty fields. :return: response parameters dict
[ "Cleanup", "response", "after", "preparing", ".", "Remove", "empty", "fields", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L327-L333
train
219,589
aiogram/aiogram
aiogram/dispatcher/webhook.py
BaseResponse.execute_response
async def execute_response(self, bot): """ Use this method if you want to execute response as simple HTTP request. :param bot: Bot instance. :return: """ method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case) method = getattr(bot, method_name, None) if method: return await method(**self.cleanup()) return await bot.request(self.method, self.cleanup())
python
async def execute_response(self, bot): """ Use this method if you want to execute response as simple HTTP request. :param bot: Bot instance. :return: """ method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case) method = getattr(bot, method_name, None) if method: return await method(**self.cleanup()) return await bot.request(self.method, self.cleanup())
[ "async", "def", "execute_response", "(", "self", ",", "bot", ")", ":", "method_name", "=", "helper", ".", "HelperMode", ".", "apply", "(", "self", ".", "method", ",", "helper", ".", "HelperMode", ".", "snake_case", ")", "method", "=", "getattr", "(", "bo...
Use this method if you want to execute response as simple HTTP request. :param bot: Bot instance. :return:
[ "Use", "this", "method", "if", "you", "want", "to", "execute", "response", "as", "simple", "HTTP", "request", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L351-L362
train
219,590
aiogram/aiogram
aiogram/dispatcher/webhook.py
ReplyToMixin.reply
def reply(self, message: typing.Union[int, types.Message]): """ Reply to message :param message: :obj:`int` or :obj:`types.Message` :return: self """ setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message) return self
python
def reply(self, message: typing.Union[int, types.Message]): """ Reply to message :param message: :obj:`int` or :obj:`types.Message` :return: self """ setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message) return self
[ "def", "reply", "(", "self", ",", "message", ":", "typing", ".", "Union", "[", "int", ",", "types", ".", "Message", "]", ")", ":", "setattr", "(", "self", ",", "'reply_to_message_id'", ",", "message", ".", "message_id", "if", "isinstance", "(", "message"...
Reply to message :param message: :obj:`int` or :obj:`types.Message` :return: self
[ "Reply", "to", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L382-L390
train
219,591
aiogram/aiogram
aiogram/dispatcher/webhook.py
ReplyToMixin.to
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]): """ Send to chat :param target: message or chat or id :return: """ if isinstance(target, types.Message): chat_id = target.chat.id elif isinstance(target, types.Chat): chat_id = target.id elif isinstance(target, (int, str)): chat_id = target else: raise TypeError(f"Bad type of target. ({type(target)})") setattr(self, 'chat_id', chat_id) return self
python
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]): """ Send to chat :param target: message or chat or id :return: """ if isinstance(target, types.Message): chat_id = target.chat.id elif isinstance(target, types.Chat): chat_id = target.id elif isinstance(target, (int, str)): chat_id = target else: raise TypeError(f"Bad type of target. ({type(target)})") setattr(self, 'chat_id', chat_id) return self
[ "def", "to", "(", "self", ",", "target", ":", "typing", ".", "Union", "[", "types", ".", "Message", ",", "types", ".", "Chat", ",", "types", ".", "base", ".", "Integer", ",", "types", ".", "base", ".", "String", "]", ")", ":", "if", "isinstance", ...
Send to chat :param target: message or chat or id :return:
[ "Send", "to", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L392-L409
train
219,592
aiogram/aiogram
aiogram/dispatcher/webhook.py
SendMessage.write
def write(self, *text, sep=' '): """ Write text to response :param text: :param sep: :return: """ self.text += markdown.text(*text, sep) return self
python
def write(self, *text, sep=' '): """ Write text to response :param text: :param sep: :return: """ self.text += markdown.text(*text, sep) return self
[ "def", "write", "(", "self", ",", "*", "text", ",", "sep", "=", "' '", ")", ":", "self", ".", "text", "+=", "markdown", ".", "text", "(", "*", "text", ",", "sep", ")", "return", "self" ]
Write text to response :param text: :param sep: :return:
[ "Write", "text", "to", "response" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L524-L533
train
219,593
aiogram/aiogram
aiogram/dispatcher/webhook.py
ForwardMessage.message
def message(self, message: types.Message): """ Select target message :param message: :return: """ setattr(self, 'from_chat_id', message.chat.id) setattr(self, 'message_id', message.message_id) return self
python
def message(self, message: types.Message): """ Select target message :param message: :return: """ setattr(self, 'from_chat_id', message.chat.id) setattr(self, 'message_id', message.message_id) return self
[ "def", "message", "(", "self", ",", "message", ":", "types", ".", "Message", ")", ":", "setattr", "(", "self", ",", "'from_chat_id'", ",", "message", ".", "chat", ".", "id", ")", "setattr", "(", "self", ",", "'message_id'", ",", "message", ".", "messag...
Select target message :param message: :return:
[ "Select", "target", "message" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L575-L584
train
219,594
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.check_address
def check_address(cls, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]): """ In all storage's methods chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. This method performs the check described above. :param chat: :param user: :return: """ if chat is None and user is None: raise ValueError('`user` or `chat` parameter is required but no one is provided!') if user is None and chat is not None: user = chat elif user is not None and chat is None: chat = user return chat, user
python
def check_address(cls, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]): """ In all storage's methods chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. This method performs the check described above. :param chat: :param user: :return: """ if chat is None and user is None: raise ValueError('`user` or `chat` parameter is required but no one is provided!') if user is None and chat is not None: user = chat elif user is not None and chat is None: chat = user return chat, user
[ "def", "check_address", "(", "cls", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ")",...
In all storage's methods chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. This method performs the check described above. :param chat: :param user: :return:
[ "In", "all", "storage", "s", "methods", "chat", "or", "user", "is", "always", "required", ".", "If", "one", "of", "them", "is", "not", "provided", "you", "have", "to", "set", "missing", "value", "based", "on", "the", "provided", "one", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L41-L61
train
219,595
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.get_data
async def get_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[typing.Dict] = None) -> typing.Dict: """ Get state-data for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return: """ raise NotImplementedError
python
async def get_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[typing.Dict] = None) -> typing.Dict: """ Get state-data for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return: """ raise NotImplementedError
[ "async", "def", "get_data", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None",...
Get state-data for user in chat. Return `default` if no data is provided in storage. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :param default: :return:
[ "Get", "state", "-", "data", "for", "user", "in", "chat", ".", "Return", "default", "if", "no", "data", "is", "provided", "in", "storage", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L80-L95
train
219,596
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.update_data
async def update_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, data: typing.Dict = None, **kwargs): """ Update data for user in chat You can use data parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param data: :param chat: :param user: :param kwargs: :return: """ raise NotImplementedError
python
async def update_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, data: typing.Dict = None, **kwargs): """ Update data for user in chat You can use data parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param data: :param chat: :param user: :param kwargs: :return: """ raise NotImplementedError
[ "async", "def", "update_data", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "Non...
Update data for user in chat You can use data parameter or|and kwargs. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param data: :param chat: :param user: :param kwargs: :return:
[ "Update", "data", "for", "user", "in", "chat" ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L129-L148
train
219,597
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.reset_state
async def reset_state(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, with_data: typing.Optional[bool] = True): """ Reset state for user in chat. You may desire to use this method when finishing conversations. Chat or user is always required. If one of this is not presented, you have to set missing value based on the provided one. :param chat: :param user: :param with_data: :return: """ chat, user = self.check_address(chat=chat, user=user) await self.set_state(chat=chat, user=user, state=None) if with_data: await self.set_data(chat=chat, user=user, data={})
python
async def reset_state(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, with_data: typing.Optional[bool] = True): """ Reset state for user in chat. You may desire to use this method when finishing conversations. Chat or user is always required. If one of this is not presented, you have to set missing value based on the provided one. :param chat: :param user: :param with_data: :return: """ chat, user = self.check_address(chat=chat, user=user) await self.set_state(chat=chat, user=user, state=None) if with_data: await self.set_data(chat=chat, user=user, data={})
[ "async", "def", "reset_state", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "Non...
Reset state for user in chat. You may desire to use this method when finishing conversations. Chat or user is always required. If one of this is not presented, you have to set missing value based on the provided one. :param chat: :param user: :param with_data: :return:
[ "Reset", "state", "for", "user", "in", "chat", ".", "You", "may", "desire", "to", "use", "this", "method", "when", "finishing", "conversations", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L165-L184
train
219,598
aiogram/aiogram
aiogram/dispatcher/storage.py
BaseStorage.finish
async def finish(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): """ Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return: """ await self.reset_state(chat=chat, user=user, with_data=True)
python
async def finish(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): """ Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return: """ await self.reset_state(chat=chat, user=user, with_data=True)
[ "async", "def", "finish", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ...
Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing value based on the provided one. :param chat: :param user: :return:
[ "Finish", "conversation", "for", "user", "in", "chat", "." ]
2af930149ce2482547721e2c8755c10307295e48
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L186-L199
train
219,599