id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
248,200 | kylejusticemagnuson/pyti | pyti/chande_momentum_oscillator.py | chande_momentum_oscillator | def chande_momentum_oscillator(close_data, period):
"""
Chande Momentum Oscillator.
Formula:
cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down))
"""
catch_errors.check_for_period_error(close_data, period)
close_data = np.array(close_data)
moving_period_diffs = [[(close_data[idx+1-period:idx+1][i] -
close_data[idx+1-period:idx+1][i-1]) for i in range(1, len(close_data[idx+1-period:idx+1]))] for idx in range(0, len(close_data))]
sum_up = []
sum_down = []
for period_diffs in moving_period_diffs:
ups = [val if val > 0 else 0 for val in period_diffs]
sum_up.append(sum(ups))
downs = [abs(val) if val < 0 else 0 for val in period_diffs]
sum_down.append(sum(downs))
sum_up = np.array(sum_up)
sum_down = np.array(sum_down)
# numpy is able to handle dividing by zero and makes those calculations
# nans which is what we want, so we safely suppress the RuntimeWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down))
return cmo | python | def chande_momentum_oscillator(close_data, period):
catch_errors.check_for_period_error(close_data, period)
close_data = np.array(close_data)
moving_period_diffs = [[(close_data[idx+1-period:idx+1][i] -
close_data[idx+1-period:idx+1][i-1]) for i in range(1, len(close_data[idx+1-period:idx+1]))] for idx in range(0, len(close_data))]
sum_up = []
sum_down = []
for period_diffs in moving_period_diffs:
ups = [val if val > 0 else 0 for val in period_diffs]
sum_up.append(sum(ups))
downs = [abs(val) if val < 0 else 0 for val in period_diffs]
sum_down.append(sum(downs))
sum_up = np.array(sum_up)
sum_down = np.array(sum_down)
# numpy is able to handle dividing by zero and makes those calculations
# nans which is what we want, so we safely suppress the RuntimeWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down))
return cmo | [
"def",
"chande_momentum_oscillator",
"(",
"close_data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"close_data",
",",
"period",
")",
"close_data",
"=",
"np",
".",
"array",
"(",
"close_data",
")",
"moving_period_diffs",
"=",
"[",
... | Chande Momentum Oscillator.
Formula:
cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) | [
"Chande",
"Momentum",
"Oscillator",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/chande_momentum_oscillator.py#L8-L37 |
248,201 | kylejusticemagnuson/pyti | pyti/price_oscillator.py | price_oscillator | def price_oscillator(data, short_period, long_period):
"""
Price Oscillator.
Formula:
(short EMA - long EMA / long EMA) * 100
"""
catch_errors.check_for_period_error(data, short_period)
catch_errors.check_for_period_error(data, long_period)
ema_short = ema(data, short_period)
ema_long = ema(data, long_period)
po = ((ema_short - ema_long) / ema_long) * 100
return po | python | def price_oscillator(data, short_period, long_period):
catch_errors.check_for_period_error(data, short_period)
catch_errors.check_for_period_error(data, long_period)
ema_short = ema(data, short_period)
ema_long = ema(data, long_period)
po = ((ema_short - ema_long) / ema_long) * 100
return po | [
"def",
"price_oscillator",
"(",
"data",
",",
"short_period",
",",
"long_period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"short_period",
")",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"long_period",
")",
"e... | Price Oscillator.
Formula:
(short EMA - long EMA / long EMA) * 100 | [
"Price",
"Oscillator",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/price_oscillator.py#L8-L22 |
248,202 | kylejusticemagnuson/pyti | pyti/catch_errors.py | check_for_period_error | def check_for_period_error(data, period):
"""
Check for Period Error.
This method checks if the developer is trying to enter a period that is
larger than the data set being entered. If that is the case an exception is
raised with a custom message that informs the developer that their period
is greater than the data set.
"""
period = int(period)
data_len = len(data)
if data_len < period:
raise Exception("Error: data_len < period") | python | def check_for_period_error(data, period):
period = int(period)
data_len = len(data)
if data_len < period:
raise Exception("Error: data_len < period") | [
"def",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
":",
"period",
"=",
"int",
"(",
"period",
")",
"data_len",
"=",
"len",
"(",
"data",
")",
"if",
"data_len",
"<",
"period",
":",
"raise",
"Exception",
"(",
"\"Error: data_len < period\"",
")"
] | Check for Period Error.
This method checks if the developer is trying to enter a period that is
larger than the data set being entered. If that is the case an exception is
raised with a custom message that informs the developer that their period
is greater than the data set. | [
"Check",
"for",
"Period",
"Error",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/catch_errors.py#L2-L14 |
248,203 | kylejusticemagnuson/pyti | pyti/catch_errors.py | check_for_input_len_diff | def check_for_input_len_diff(*args):
"""
Check for Input Length Difference.
This method checks if multiple data sets that are inputted are all the same
size. If they are not the same length an error is raised with a custom
message that informs the developer that the data set's lengths are not the
same.
"""
arrays_len = [len(arr) for arr in args]
if not all(a == arrays_len[0] for a in arrays_len):
err_msg = ("Error: mismatched data lengths, check to ensure that all "
"input data is the same length and valid")
raise Exception(err_msg) | python | def check_for_input_len_diff(*args):
arrays_len = [len(arr) for arr in args]
if not all(a == arrays_len[0] for a in arrays_len):
err_msg = ("Error: mismatched data lengths, check to ensure that all "
"input data is the same length and valid")
raise Exception(err_msg) | [
"def",
"check_for_input_len_diff",
"(",
"*",
"args",
")",
":",
"arrays_len",
"=",
"[",
"len",
"(",
"arr",
")",
"for",
"arr",
"in",
"args",
"]",
"if",
"not",
"all",
"(",
"a",
"==",
"arrays_len",
"[",
"0",
"]",
"for",
"a",
"in",
"arrays_len",
")",
":... | Check for Input Length Difference.
This method checks if multiple data sets that are inputted are all the same
size. If they are not the same length an error is raised with a custom
message that informs the developer that the data set's lengths are not the
same. | [
"Check",
"for",
"Input",
"Length",
"Difference",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/catch_errors.py#L17-L30 |
248,204 | kylejusticemagnuson/pyti | pyti/bollinger_bands.py | upper_bollinger_band | def upper_bollinger_band(data, period, std_mult=2.0):
"""
Upper Bollinger Band.
Formula:
u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
simple_ma = sma(data, period)[period-1:]
upper_bb = []
for idx in range(len(data) - period + 1):
std_dev = np.std(data[idx:idx + period])
upper_bb.append(simple_ma[idx] + std_dev * std_mult)
upper_bb = fill_for_noncomputable_vals(data, upper_bb)
return np.array(upper_bb) | python | def upper_bollinger_band(data, period, std_mult=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
simple_ma = sma(data, period)[period-1:]
upper_bb = []
for idx in range(len(data) - period + 1):
std_dev = np.std(data[idx:idx + period])
upper_bb.append(simple_ma[idx] + std_dev * std_mult)
upper_bb = fill_for_noncomputable_vals(data, upper_bb)
return np.array(upper_bb) | [
"def",
"upper_bollinger_band",
"(",
"data",
",",
"period",
",",
"std_mult",
"=",
"2.0",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"simple_ma",
"=",
"sma",
"(",
"data"... | Upper Bollinger Band.
Formula:
u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult | [
"Upper",
"Bollinger",
"Band",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L11-L29 |
248,205 | kylejusticemagnuson/pyti | pyti/bollinger_bands.py | middle_bollinger_band | def middle_bollinger_band(data, period, std=2.0):
"""
Middle Bollinger Band.
Formula:
m_bb = sma()
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
mid_bb = sma(data, period)
return mid_bb | python | def middle_bollinger_band(data, period, std=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
mid_bb = sma(data, period)
return mid_bb | [
"def",
"middle_bollinger_band",
"(",
"data",
",",
"period",
",",
"std",
"=",
"2.0",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"mid_bb",
"=",
"sma",
"(",
"data",
","... | Middle Bollinger Band.
Formula:
m_bb = sma() | [
"Middle",
"Bollinger",
"Band",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L32-L44 |
248,206 | kylejusticemagnuson/pyti | pyti/bollinger_bands.py | lower_bollinger_band | def lower_bollinger_band(data, period, std=2.0):
"""
Lower Bollinger Band.
Formula:
u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
simple_ma = sma(data, period)[period-1:]
lower_bb = []
for idx in range(len(data) - period + 1):
std_dev = np.std(data[idx:idx + period])
lower_bb.append(simple_ma[idx] - std_dev * std)
lower_bb = fill_for_noncomputable_vals(data, lower_bb)
return np.array(lower_bb) | python | def lower_bollinger_band(data, period, std=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
simple_ma = sma(data, period)[period-1:]
lower_bb = []
for idx in range(len(data) - period + 1):
std_dev = np.std(data[idx:idx + period])
lower_bb.append(simple_ma[idx] - std_dev * std)
lower_bb = fill_for_noncomputable_vals(data, lower_bb)
return np.array(lower_bb) | [
"def",
"lower_bollinger_band",
"(",
"data",
",",
"period",
",",
"std",
"=",
"2.0",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"simple_ma",
"=",
"sma",
"(",
"data",
"... | Lower Bollinger Band.
Formula:
u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult | [
"Lower",
"Bollinger",
"Band",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L47-L65 |
248,207 | kylejusticemagnuson/pyti | pyti/bollinger_bands.py | percent_bandwidth | def percent_bandwidth(data, period, std=2.0):
"""
Percent Bandwidth.
Formula:
%_bw = data() - l_bb() / bb_range()
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
percent_bandwidth = ((np.array(data) -
lower_bollinger_band(data, period, std)) /
bb_range(data, period, std)
)
return percent_bandwidth | python | def percent_bandwidth(data, period, std=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
percent_bandwidth = ((np.array(data) -
lower_bollinger_band(data, period, std)) /
bb_range(data, period, std)
)
return percent_bandwidth | [
"def",
"percent_bandwidth",
"(",
"data",
",",
"period",
",",
"std",
"=",
"2.0",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"percent_bandwidth",
"=",
"(",
"(",
"np",
... | Percent Bandwidth.
Formula:
%_bw = data() - l_bb() / bb_range() | [
"Percent",
"Bandwidth",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L102-L117 |
248,208 | kylejusticemagnuson/pyti | pyti/standard_deviation.py | standard_deviation | def standard_deviation(data, period):
"""
Standard Deviation.
Formula:
std = sqrt(avg(abs(x - avg(x))^2))
"""
catch_errors.check_for_period_error(data, period)
stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]
stds = fill_for_noncomputable_vals(data, stds)
return stds | python | def standard_deviation(data, period):
catch_errors.check_for_period_error(data, period)
stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]
stds = fill_for_noncomputable_vals(data, stds)
return stds | [
"def",
"standard_deviation",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"stds",
"=",
"[",
"np",
".",
"std",
"(",
"data",
"[",
"idx",
"+",
"1",
"-",
"period",
":",
"idx",
"+",
... | Standard Deviation.
Formula:
std = sqrt(avg(abs(x - avg(x))^2)) | [
"Standard",
"Deviation",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/standard_deviation.py#L8-L20 |
248,209 | kylejusticemagnuson/pyti | pyti/detrended_price_oscillator.py | detrended_price_oscillator | def detrended_price_oscillator(data, period):
"""
Detrended Price Oscillator.
Formula:
DPO = DATA[i] - Avg(DATA[period/2 + 1])
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))]
dop = fill_for_noncomputable_vals(data, dop)
return dop | python | def detrended_price_oscillator(data, period):
catch_errors.check_for_period_error(data, period)
period = int(period)
dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))]
dop = fill_for_noncomputable_vals(data, dop)
return dop | [
"def",
"detrended_price_oscillator",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"dop",
"=",
"[",
"data",
"[",
"idx",
"]",
"-",
"np",
".",... | Detrended Price Oscillator.
Formula:
DPO = DATA[i] - Avg(DATA[period/2 + 1]) | [
"Detrended",
"Price",
"Oscillator",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/detrended_price_oscillator.py#L8-L19 |
248,210 | kylejusticemagnuson/pyti | pyti/smoothed_moving_average.py | smoothed_moving_average | def smoothed_moving_average(data, period):
"""
Smoothed Moving Average.
Formula:
smma = avg(data(n)) - avg(data(n)/n) + data(t)/n
"""
catch_errors.check_for_period_error(data, period)
series = pd.Series(data)
return series.ewm(alpha = 1.0/period).mean().values.flatten() | python | def smoothed_moving_average(data, period):
catch_errors.check_for_period_error(data, period)
series = pd.Series(data)
return series.ewm(alpha = 1.0/period).mean().values.flatten() | [
"def",
"smoothed_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"series",
"=",
"pd",
".",
"Series",
"(",
"data",
")",
"return",
"series",
".",
"ewm",
"(",
"alpha",
"=",... | Smoothed Moving Average.
Formula:
smma = avg(data(n)) - avg(data(n)/n) + data(t)/n | [
"Smoothed",
"Moving",
"Average",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/smoothed_moving_average.py#L9-L18 |
248,211 | kylejusticemagnuson/pyti | pyti/chaikin_money_flow.py | chaikin_money_flow | def chaikin_money_flow(close_data, high_data, low_data, volume, period):
"""
Chaikin Money Flow.
Formula:
CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn)
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume)
catch_errors.check_for_period_error(close_data, period)
close_data = np.array(close_data)
high_data = np.array(high_data)
low_data = np.array(low_data)
volume = np.array(volume)
cmf = [sum((((close_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1]) -
(high_data[idx+1-period:idx+1] - close_data[idx+1-period:idx+1])) /
(high_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1])) *
volume[idx+1-period:idx+1]) / sum(volume[idx+1-period:idx+1]) for idx in range(period-1, len(close_data))]
cmf = fill_for_noncomputable_vals(close_data, cmf)
return cmf | python | def chaikin_money_flow(close_data, high_data, low_data, volume, period):
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume)
catch_errors.check_for_period_error(close_data, period)
close_data = np.array(close_data)
high_data = np.array(high_data)
low_data = np.array(low_data)
volume = np.array(volume)
cmf = [sum((((close_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1]) -
(high_data[idx+1-period:idx+1] - close_data[idx+1-period:idx+1])) /
(high_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1])) *
volume[idx+1-period:idx+1]) / sum(volume[idx+1-period:idx+1]) for idx in range(period-1, len(close_data))]
cmf = fill_for_noncomputable_vals(close_data, cmf)
return cmf | [
"def",
"chaikin_money_flow",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
"catch_errors",
... | Chaikin Money Flow.
Formula:
CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn) | [
"Chaikin",
"Money",
"Flow",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/chaikin_money_flow.py#L8-L28 |
248,212 | kylejusticemagnuson/pyti | pyti/hull_moving_average.py | hull_moving_average | def hull_moving_average(data, period):
"""
Hull Moving Average.
Formula:
HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
"""
catch_errors.check_for_period_error(data, period)
hma = wma(
2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period))
)
return hma | python | def hull_moving_average(data, period):
catch_errors.check_for_period_error(data, period)
hma = wma(
2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period))
)
return hma | [
"def",
"hull_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"hma",
"=",
"wma",
"(",
"2",
"*",
"wma",
"(",
"data",
",",
"int",
"(",
"period",
"/",
"2",
")",
")",
"... | Hull Moving Average.
Formula:
HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n) | [
"Hull",
"Moving",
"Average",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/hull_moving_average.py#L9-L20 |
248,213 | kylejusticemagnuson/pyti | pyti/standard_variance.py | standard_variance | def standard_variance(data, period):
"""
Standard Variance.
Formula:
(Ct - AVGt)^2 / N
"""
catch_errors.check_for_period_error(data, period)
sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]
sv = fill_for_noncomputable_vals(data, sv)
return sv | python | def standard_variance(data, period):
catch_errors.check_for_period_error(data, period)
sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]
sv = fill_for_noncomputable_vals(data, sv)
return sv | [
"def",
"standard_variance",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"sv",
"=",
"[",
"np",
".",
"var",
"(",
"data",
"[",
"idx",
"+",
"1",
"-",
"period",
":",
"idx",
"+",
"1"... | Standard Variance.
Formula:
(Ct - AVGt)^2 / N | [
"Standard",
"Variance",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/standard_variance.py#L8-L19 |
248,214 | kylejusticemagnuson/pyti | pyti/directional_indicators.py | calculate_up_moves | def calculate_up_moves(high_data):
"""
Up Move.
Formula:
UPMOVE = Ht - Ht-1
"""
up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))]
return [np.nan] + up_moves | python | def calculate_up_moves(high_data):
up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))]
return [np.nan] + up_moves | [
"def",
"calculate_up_moves",
"(",
"high_data",
")",
":",
"up_moves",
"=",
"[",
"high_data",
"[",
"idx",
"]",
"-",
"high_data",
"[",
"idx",
"-",
"1",
"]",
"for",
"idx",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"high_data",
")",
")",
"]",
"return",
... | Up Move.
Formula:
UPMOVE = Ht - Ht-1 | [
"Up",
"Move",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L13-L21 |
248,215 | kylejusticemagnuson/pyti | pyti/directional_indicators.py | calculate_down_moves | def calculate_down_moves(low_data):
"""
Down Move.
Formula:
DWNMOVE = Lt-1 - Lt
"""
down_moves = [low_data[idx-1] - low_data[idx] for idx in range(1, len(low_data))]
return [np.nan] + down_moves | python | def calculate_down_moves(low_data):
down_moves = [low_data[idx-1] - low_data[idx] for idx in range(1, len(low_data))]
return [np.nan] + down_moves | [
"def",
"calculate_down_moves",
"(",
"low_data",
")",
":",
"down_moves",
"=",
"[",
"low_data",
"[",
"idx",
"-",
"1",
"]",
"-",
"low_data",
"[",
"idx",
"]",
"for",
"idx",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"low_data",
")",
")",
"]",
"return",
... | Down Move.
Formula:
DWNMOVE = Lt-1 - Lt | [
"Down",
"Move",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L24-L32 |
248,216 | kylejusticemagnuson/pyti | pyti/directional_indicators.py | average_directional_index | def average_directional_index(close_data, high_data, low_data, period):
"""
Average Directional Index.
Formula:
ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
"""
avg_di = (abs(
(positive_directional_index(
close_data, high_data, low_data, period) -
negative_directional_index(
close_data, high_data, low_data, period)) /
(positive_directional_index(
close_data, high_data, low_data, period) +
negative_directional_index(
close_data, high_data, low_data, period)))
)
adx = 100 * smma(avg_di, period)
return adx | python | def average_directional_index(close_data, high_data, low_data, period):
avg_di = (abs(
(positive_directional_index(
close_data, high_data, low_data, period) -
negative_directional_index(
close_data, high_data, low_data, period)) /
(positive_directional_index(
close_data, high_data, low_data, period) +
negative_directional_index(
close_data, high_data, low_data, period)))
)
adx = 100 * smma(avg_di, period)
return adx | [
"def",
"average_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
":",
"avg_di",
"=",
"(",
"abs",
"(",
"(",
"positive_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
"-",... | Average Directional Index.
Formula:
ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI))) | [
"Average",
"Directional",
"Index",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L107-L125 |
248,217 | kylejusticemagnuson/pyti | pyti/linear_weighted_moving_average.py | linear_weighted_moving_average | def linear_weighted_moving_average(data, period):
"""
Linear Weighted Moving Average.
Formula:
LWMA = SUM(DATA[i]) * i / SUM(i)
"""
catch_errors.check_for_period_error(data, period)
idx_period = list(range(1, period+1))
lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]
for i in data[idx-(period-1):idx+1]])) /
sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]
lwma = fill_for_noncomputable_vals(data, lwma)
return lwma | python | def linear_weighted_moving_average(data, period):
catch_errors.check_for_period_error(data, period)
idx_period = list(range(1, period+1))
lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]
for i in data[idx-(period-1):idx+1]])) /
sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]
lwma = fill_for_noncomputable_vals(data, lwma)
return lwma | [
"def",
"linear_weighted_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"idx_period",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"period",
"+",
"1",
")",
")",
"lwma",
"="... | Linear Weighted Moving Average.
Formula:
LWMA = SUM(DATA[i]) * i / SUM(i) | [
"Linear",
"Weighted",
"Moving",
"Average",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/linear_weighted_moving_average.py#L7-L21 |
248,218 | kylejusticemagnuson/pyti | pyti/volume_oscillator.py | volume_oscillator | def volume_oscillator(volume, short_period, long_period):
"""
Volume Oscillator.
Formula:
vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
"""
catch_errors.check_for_period_error(volume, short_period)
catch_errors.check_for_period_error(volume, long_period)
vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) /
sma(volume, long_period)))
return vo | python | def volume_oscillator(volume, short_period, long_period):
catch_errors.check_for_period_error(volume, short_period)
catch_errors.check_for_period_error(volume, long_period)
vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) /
sma(volume, long_period)))
return vo | [
"def",
"volume_oscillator",
"(",
"volume",
",",
"short_period",
",",
"long_period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"volume",
",",
"short_period",
")",
"catch_errors",
".",
"check_for_period_error",
"(",
"volume",
",",
"long_period",
")... | Volume Oscillator.
Formula:
vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long)) | [
"Volume",
"Oscillator",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/volume_oscillator.py#L6-L18 |
248,219 | kylejusticemagnuson/pyti | pyti/triple_exponential_moving_average.py | triple_exponential_moving_average | def triple_exponential_moving_average(data, period):
"""
Triple Exponential Moving Average.
Formula:
TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
"""
catch_errors.check_for_period_error(data, period)
tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) +
ema(ema(ema(data, period), period), period)
)
return tema | python | def triple_exponential_moving_average(data, period):
catch_errors.check_for_period_error(data, period)
tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) +
ema(ema(ema(data, period), period), period)
)
return tema | [
"def",
"triple_exponential_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"tema",
"=",
"(",
"(",
"3",
"*",
"ema",
"(",
"data",
",",
"period",
")",
"-",
"(",
"3",
"*",... | Triple Exponential Moving Average.
Formula:
TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA)) | [
"Triple",
"Exponential",
"Moving",
"Average",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/triple_exponential_moving_average.py#L8-L20 |
248,220 | kylejusticemagnuson/pyti | pyti/money_flow.py | money_flow | def money_flow(close_data, high_data, low_data, volume):
"""
Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
mf = volume * tp(close_data, high_data, low_data)
return mf | python | def money_flow(close_data, high_data, low_data, volume):
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
mf = volume * tp(close_data, high_data, low_data)
return mf | [
"def",
"money_flow",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
"mf",
"=",
"volume",
"*",
"tp",
"("... | Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE | [
"Money",
"Flow",
"."
] | 2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2 | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/money_flow.py#L6-L17 |
248,221 | mrooney/mintapi | mintapi/api.py | Mint.request_and_check | def request_and_check(self, url, method='get',
expected_content_type=None, **kwargs):
"""Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type: prefix to match response content-type against
**kwargs: passed to the request method directly.
Raises:
RuntimeError if status_code does not match.
"""
assert method in ['get', 'post']
result = self.driver.request(method, url, **kwargs)
if result.status_code != requests.codes.ok:
raise RuntimeError('Error requesting %r, status = %d' %
(url, result.status_code))
if expected_content_type is not None:
content_type = result.headers.get('content-type', '')
if not re.match(expected_content_type, content_type):
raise RuntimeError(
'Error requesting %r, content type %r does not match %r' %
(url, content_type, expected_content_type))
return result | python | def request_and_check(self, url, method='get',
expected_content_type=None, **kwargs):
assert method in ['get', 'post']
result = self.driver.request(method, url, **kwargs)
if result.status_code != requests.codes.ok:
raise RuntimeError('Error requesting %r, status = %d' %
(url, result.status_code))
if expected_content_type is not None:
content_type = result.headers.get('content-type', '')
if not re.match(expected_content_type, content_type):
raise RuntimeError(
'Error requesting %r, content type %r does not match %r' %
(url, content_type, expected_content_type))
return result | [
"def",
"request_and_check",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'get'",
",",
"expected_content_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"method",
"in",
"[",
"'get'",
",",
"'post'",
"]",
"result",
"=",
"self",
".",
"dri... | Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type: prefix to match response content-type against
**kwargs: passed to the request method directly.
Raises:
RuntimeError if status_code does not match. | [
"Performs",
"a",
"request",
"and",
"checks",
"that",
"the",
"status",
"is",
"OK",
"and",
"that",
"the",
"content",
"-",
"type",
"matches",
"expectations",
"."
] | 44fddbeac79a68da657ad8118e02fcde968f8dfe | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L394-L419 |
248,222 | mrooney/mintapi | mintapi/api.py | Mint.get_transactions_json | def get_transactions_json(self, include_investment=False,
skip_duplicates=False, start_date=None, id=0):
"""Returns the raw JSON transaction data as downloaded from Mint. The JSON
transaction data includes some additional information missing from the
CSV data, such as whether the transaction is pending or completed, but
leaves off the year for current year transactions.
Warning: In order to reliably include or exclude duplicates, it is
necessary to change the user account property 'hide_duplicates' to the
appropriate value. This affects what is displayed in the web
interface. Note that the CSV transactions never exclude duplicates.
"""
# Warning: This is a global property for the user that we are changing.
self.set_user_property(
'hide_duplicates', 'T' if skip_duplicates else 'F')
# Converts the start date into datetime format - must be mm/dd/yy
try:
start_date = datetime.strptime(start_date, '%m/%d/%y')
except (TypeError, ValueError):
start_date = None
all_txns = []
offset = 0
# Mint only returns some of the transactions at once. To get all of
# them, we have to keep asking for more until we reach the end.
while 1:
url = MINT_ROOT_URL + '/getJsonData.xevent'
params = {
'queryNew': '',
'offset': offset,
'comparableType': '8',
'rnd': Mint.get_rnd(),
}
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
if id > 0 or include_investment:
params['id'] = id
if include_investment:
params['task'] = 'transactions'
else:
params['task'] = 'transactions,txnfilters'
params['filterType'] = 'cash'
result = self.request_and_check(
url, headers=JSON_HEADER, params=params,
expected_content_type='text/json|application/json')
data = json.loads(result.text)
txns = data['set'][0].get('data', [])
if not txns:
break
if start_date:
last_dt = json_date_to_datetime(txns[-1]['odate'])
if last_dt < start_date:
keep_txns = [
t for t in txns
if json_date_to_datetime(t['odate']) >= start_date]
all_txns.extend(keep_txns)
break
all_txns.extend(txns)
offset += len(txns)
return all_txns | python | def get_transactions_json(self, include_investment=False,
skip_duplicates=False, start_date=None, id=0):
# Warning: This is a global property for the user that we are changing.
self.set_user_property(
'hide_duplicates', 'T' if skip_duplicates else 'F')
# Converts the start date into datetime format - must be mm/dd/yy
try:
start_date = datetime.strptime(start_date, '%m/%d/%y')
except (TypeError, ValueError):
start_date = None
all_txns = []
offset = 0
# Mint only returns some of the transactions at once. To get all of
# them, we have to keep asking for more until we reach the end.
while 1:
url = MINT_ROOT_URL + '/getJsonData.xevent'
params = {
'queryNew': '',
'offset': offset,
'comparableType': '8',
'rnd': Mint.get_rnd(),
}
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
if id > 0 or include_investment:
params['id'] = id
if include_investment:
params['task'] = 'transactions'
else:
params['task'] = 'transactions,txnfilters'
params['filterType'] = 'cash'
result = self.request_and_check(
url, headers=JSON_HEADER, params=params,
expected_content_type='text/json|application/json')
data = json.loads(result.text)
txns = data['set'][0].get('data', [])
if not txns:
break
if start_date:
last_dt = json_date_to_datetime(txns[-1]['odate'])
if last_dt < start_date:
keep_txns = [
t for t in txns
if json_date_to_datetime(t['odate']) >= start_date]
all_txns.extend(keep_txns)
break
all_txns.extend(txns)
offset += len(txns)
return all_txns | [
"def",
"get_transactions_json",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"skip_duplicates",
"=",
"False",
",",
"start_date",
"=",
"None",
",",
"id",
"=",
"0",
")",
":",
"# Warning: This is a global property for the user that we are changing.",
"self",
... | Returns the raw JSON transaction data as downloaded from Mint. The JSON
transaction data includes some additional information missing from the
CSV data, such as whether the transaction is pending or completed, but
leaves off the year for current year transactions.
Warning: In order to reliably include or exclude duplicates, it is
necessary to change the user account property 'hide_duplicates' to the
appropriate value. This affects what is displayed in the web
interface. Note that the CSV transactions never exclude duplicates. | [
"Returns",
"the",
"raw",
"JSON",
"transaction",
"data",
"as",
"downloaded",
"from",
"Mint",
".",
"The",
"JSON",
"transaction",
"data",
"includes",
"some",
"additional",
"information",
"missing",
"from",
"the",
"CSV",
"data",
"such",
"as",
"whether",
"the",
"tr... | 44fddbeac79a68da657ad8118e02fcde968f8dfe | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L533-L594 |
248,223 | mrooney/mintapi | mintapi/api.py | Mint.get_detailed_transactions | def get_detailed_transactions(self, include_investment=False,
skip_duplicates=False,
remove_pending=True,
start_date=None):
"""Returns the JSON transaction data as a DataFrame, and converts
current year dates and prior year dates into consistent datetime
format, and reverses credit activity.
Note: start_date must be in format mm/dd/yy. If pulls take too long,
use a more recent start date. See json explanations of
include_investment and skip_duplicates.
Also note: Mint includes pending transactions, however these sometimes
change dates/amounts after the transactions post. They have been
removed by default in this pull, but can be included by changing
remove_pending to False
"""
assert_pd()
result = self.get_transactions_json(include_investment,
skip_duplicates, start_date)
df = pd.DataFrame(result)
df['odate'] = df['odate'].apply(json_date_to_datetime)
if remove_pending:
df = df[~df.isPending]
df.reset_index(drop=True, inplace=True)
df.amount = df.apply(reverse_credit_amount, axis=1)
return df | python | def get_detailed_transactions(self, include_investment=False,
skip_duplicates=False,
remove_pending=True,
start_date=None):
assert_pd()
result = self.get_transactions_json(include_investment,
skip_duplicates, start_date)
df = pd.DataFrame(result)
df['odate'] = df['odate'].apply(json_date_to_datetime)
if remove_pending:
df = df[~df.isPending]
df.reset_index(drop=True, inplace=True)
df.amount = df.apply(reverse_credit_amount, axis=1)
return df | [
"def",
"get_detailed_transactions",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"skip_duplicates",
"=",
"False",
",",
"remove_pending",
"=",
"True",
",",
"start_date",
"=",
"None",
")",
":",
"assert_pd",
"(",
")",
"result",
"=",
"self",
".",
"... | Returns the JSON transaction data as a DataFrame, and converts
current year dates and prior year dates into consistent datetime
format, and reverses credit activity.
Note: start_date must be in format mm/dd/yy. If pulls take too long,
use a more recent start date. See json explanations of
include_investment and skip_duplicates.
Also note: Mint includes pending transactions, however these sometimes
change dates/amounts after the transactions post. They have been
removed by default in this pull, but can be included by changing
remove_pending to False | [
"Returns",
"the",
"JSON",
"transaction",
"data",
"as",
"a",
"DataFrame",
"and",
"converts",
"current",
"year",
"dates",
"and",
"prior",
"year",
"dates",
"into",
"consistent",
"datetime",
"format",
"and",
"reverses",
"credit",
"activity",
"."
] | 44fddbeac79a68da657ad8118e02fcde968f8dfe | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L596-L627 |
248,224 | mrooney/mintapi | mintapi/api.py | Mint.get_transactions_csv | def get_transactions_csv(self, include_investment=False, acct=0):
"""Returns the raw CSV transaction data as downloaded from Mint.
If include_investment == True, also includes transactions that Mint
classifies as investment-related. You may find that the investment
transaction data is not sufficiently detailed to actually be useful,
however.
"""
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
params = None
if include_investment or acct > 0:
params = {'accountId': acct}
result = self.request_and_check(
'{}/transactionDownload.event'.format(MINT_ROOT_URL),
params=params,
expected_content_type='text/csv')
return result.content | python | def get_transactions_csv(self, include_investment=False, acct=0):
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
params = None
if include_investment or acct > 0:
params = {'accountId': acct}
result = self.request_and_check(
'{}/transactionDownload.event'.format(MINT_ROOT_URL),
params=params,
expected_content_type='text/csv')
return result.content | [
"def",
"get_transactions_csv",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"acct",
"=",
"0",
")",
":",
"# Specifying accountId=0 causes Mint to return investment",
"# transactions as well. Otherwise they are skipped by",
"# default.",
"params",
"=",
"None",
"i... | Returns the raw CSV transaction data as downloaded from Mint.
If include_investment == True, also includes transactions that Mint
classifies as investment-related. You may find that the investment
transaction data is not sufficiently detailed to actually be useful,
however. | [
"Returns",
"the",
"raw",
"CSV",
"transaction",
"data",
"as",
"downloaded",
"from",
"Mint",
"."
] | 44fddbeac79a68da657ad8118e02fcde968f8dfe | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L629-L648 |
248,225 | mrooney/mintapi | mintapi/api.py | Mint.get_transactions | def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.columns = [c.lower().replace(' ', '_') for c in df.columns]
df.category = (df.category.str.lower()
.replace('uncategorized', pd.np.nan))
return df | python | def get_transactions(self, include_investment=False):
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.columns = [c.lower().replace(' ', '_') for c in df.columns]
df.category = (df.category.str.lower()
.replace('uncategorized', pd.np.nan))
return df | [
"def",
"get_transactions",
"(",
"self",
",",
"include_investment",
"=",
"False",
")",
":",
"assert_pd",
"(",
")",
"s",
"=",
"StringIO",
"(",
"self",
".",
"get_transactions_csv",
"(",
"include_investment",
"=",
"include_investment",
")",
")",
"s",
".",
"seek",
... | Returns the transaction data as a Pandas DataFrame. | [
"Returns",
"the",
"transaction",
"data",
"as",
"a",
"Pandas",
"DataFrame",
"."
] | 44fddbeac79a68da657ad8118e02fcde968f8dfe | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L662-L672 |
248,226 | StellarCN/py-stellar-base | stellar_base/address.py | Address.payments | def payments(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the payments JSON from this instance's Horizon server.
Retrieve the payments JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def payments(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"payments",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_payments",
"(",
"address",
"=",
"self",
".",
"address... | Retrieve the payments JSON from this instance's Horizon server.
Retrieve the payments JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses. | [
"Retrieve",
"the",
"payments",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L95-L109 |
248,227 | StellarCN/py-stellar-base | stellar_base/address.py | Address.offers | def offers(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the offers JSON from this instance's Horizon server.
Retrieve the offers JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def offers(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"offers",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_offers",
"(",
"self",
".",
"address",
",",
"cursor",
... | Retrieve the offers JSON from this instance's Horizon server.
Retrieve the offers JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses. | [
"Retrieve",
"the",
"offers",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L111-L125 |
248,228 | StellarCN/py-stellar-base | stellar_base/address.py | Address.transactions | def transactions(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_transactions(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def transactions(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_transactions(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"transactions",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_transactions",
"(",
"self",
".",
"address",
",",
... | Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses. | [
"Retrieve",
"the",
"transactions",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L127-L141 |
248,229 | StellarCN/py-stellar-base | stellar_base/address.py | Address.operations | def operations(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the operations JSON from this instance's Horizon server.
Retrieve the operations JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_operations(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def operations(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_operations(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"operations",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_operations",
"(",
"self",
".",
"address",
",",
"cur... | Retrieve the operations JSON from this instance's Horizon server.
Retrieve the operations JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon. | [
"Retrieve",
"the",
"operations",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L143-L158 |
248,230 | StellarCN/py-stellar-base | stellar_base/address.py | Address.trades | def trades(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_trades(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def trades(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_trades(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"trades",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_trades",
"(",
"self",
".",
"address",
",",
"cursor",
... | Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon. | [
"Retrieve",
"the",
"trades",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L160-L174 |
248,231 | StellarCN/py-stellar-base | stellar_base/address.py | Address.effects | def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the effects JSON from this instance's Horizon server.
Retrieve the effects JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_effects(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | python | def effects(self, cursor=None, order='asc', limit=10, sse=False):
return self.horizon.account_effects(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | [
"def",
"effects",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_effects",
"(",
"self",
".",
"address",
",",
"cursor",
... | Retrieve the effects JSON from this instance's Horizon server.
Retrieve the effects JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon. | [
"Retrieve",
"the",
"effects",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L176-L191 |
248,232 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.submit | def submit(self, te):
"""Submit the transaction using a pooled connection, and retry on failure.
`POST /transactions
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_
Uses form-encoded data to send over to Horizon.
:return: The JSON response indicating the success/failure of the
submitted transaction.
:rtype: dict
"""
params = {'tx': te}
url = urljoin(self.horizon_uri, 'transactions/')
# POST is not included in Retry's method_whitelist for a good reason.
# our custom retry mechanism follows
reply = None
retry_count = self.num_retries
while True:
try:
reply = self._session.post(
url, data=params, timeout=self.request_timeout)
return check_horizon_reply(reply.json())
except (RequestException, NewConnectionError, ValueError) as e:
if reply is not None:
msg = 'Horizon submit exception: {}, reply: [{}] {}'.format(
str(e), reply.status_code, reply.text)
else:
msg = 'Horizon submit exception: {}'.format(str(e))
logging.warning(msg)
if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0:
if reply is None:
raise HorizonRequestError(e)
raise HorizonError('Invalid horizon reply: [{}] {}'.format(
reply.status_code, reply.text), reply.status_code)
retry_count -= 1
logging.warning('Submit retry attempt {}'.format(retry_count))
sleep(self.backoff_factor) | python | def submit(self, te):
params = {'tx': te}
url = urljoin(self.horizon_uri, 'transactions/')
# POST is not included in Retry's method_whitelist for a good reason.
# our custom retry mechanism follows
reply = None
retry_count = self.num_retries
while True:
try:
reply = self._session.post(
url, data=params, timeout=self.request_timeout)
return check_horizon_reply(reply.json())
except (RequestException, NewConnectionError, ValueError) as e:
if reply is not None:
msg = 'Horizon submit exception: {}, reply: [{}] {}'.format(
str(e), reply.status_code, reply.text)
else:
msg = 'Horizon submit exception: {}'.format(str(e))
logging.warning(msg)
if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0:
if reply is None:
raise HorizonRequestError(e)
raise HorizonError('Invalid horizon reply: [{}] {}'.format(
reply.status_code, reply.text), reply.status_code)
retry_count -= 1
logging.warning('Submit retry attempt {}'.format(retry_count))
sleep(self.backoff_factor) | [
"def",
"submit",
"(",
"self",
",",
"te",
")",
":",
"params",
"=",
"{",
"'tx'",
":",
"te",
"}",
"url",
"=",
"urljoin",
"(",
"self",
".",
"horizon_uri",
",",
"'transactions/'",
")",
"# POST is not included in Retry's method_whitelist for a good reason.",
"# our cust... | Submit the transaction using a pooled connection, and retry on failure.
`POST /transactions
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_
Uses form-encoded data to send over to Horizon.
:return: The JSON response indicating the success/failure of the
submitted transaction.
:rtype: dict | [
"Submit",
"the",
"transaction",
"using",
"a",
"pooled",
"connection",
"and",
"retry",
"on",
"failure",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L118-L158 |
248,233 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.account | def account(self, address):
"""Returns information and links relating to a single account.
`GET /accounts/{account}
<https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_
:param str address: The account ID to retrieve details about.
:return: The account details in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}'.format(account_id=address)
return self.query(endpoint) | python | def account(self, address):
endpoint = '/accounts/{account_id}'.format(account_id=address)
return self.query(endpoint) | [
"def",
"account",
"(",
"self",
",",
"address",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}'",
".",
"format",
"(",
"account_id",
"=",
"address",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] | Returns information and links relating to a single account.
`GET /accounts/{account}
<https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_
:param str address: The account ID to retrieve details about.
:return: The account details in a JSON response.
:rtype: dict | [
"Returns",
"information",
"and",
"links",
"relating",
"to",
"a",
"single",
"account",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L188-L200 |
248,234 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.account_data | def account_data(self, address, key):
"""This endpoint represents a single data associated with a given
account.
`GET /accounts/{account}/data/{key}
<https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_
:param str address: The account ID to look up a data item from.
:param str key: The name of the key for the data item in question.
:return: The value of the data field for the given account and data key.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/data/{data_key}'.format(
account_id=address, data_key=key)
return self.query(endpoint) | python | def account_data(self, address, key):
endpoint = '/accounts/{account_id}/data/{data_key}'.format(
account_id=address, data_key=key)
return self.query(endpoint) | [
"def",
"account_data",
"(",
"self",
",",
"address",
",",
"key",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}/data/{data_key}'",
".",
"format",
"(",
"account_id",
"=",
"address",
",",
"data_key",
"=",
"key",
")",
"return",
"self",
".",
"query",
"(",
"e... | This endpoint represents a single data associated with a given
account.
`GET /accounts/{account}/data/{key}
<https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_
:param str address: The account ID to look up a data item from.
:param str key: The name of the key for the data item in question.
:return: The value of the data field for the given account and data key.
:rtype: dict | [
"This",
"endpoint",
"represents",
"a",
"single",
"data",
"associated",
"with",
"a",
"given",
"account",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L202-L217 |
248,235 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.account_effects | def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects that changed a given account.
`GET /accounts/{account}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_
:param str address: The account ID to look up effects for.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: The list of effects in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/effects'.format(account_id=address)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse) | python | def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False):
endpoint = '/accounts/{account_id}/effects'.format(account_id=address)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse) | [
"def",
"account_effects",
"(",
"self",
",",
"address",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}/effects'",
".",
"format",
"(",
"account_id... | This endpoint represents all effects that changed a given account.
`GET /accounts/{account}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_
:param str address: The account ID to look up effects for.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: The list of effects in a JSON response.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"changed",
"a",
"given",
"account",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L219-L238 |
248,236 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.assets | def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10):
"""This endpoint represents all assets. It will give you all the assets
in the system along with various statistics about each.
See the documentation below for details on query parameters that are
available.
`GET /assets{?asset_code,asset_issuer,cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_
:param str asset_code: Code of the Asset to filter by.
:param str asset_issuer: Issuer of the Asset to filter by.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc",
ordered by asset_code then by asset_issuer.
:param int limit: Maximum number of records to return.
:return: A list of all valid payment operations
:rtype: dict
"""
endpoint = '/assets'
params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order,
limit=limit)
return self.query(endpoint, params) | python | def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10):
endpoint = '/assets'
params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order,
limit=limit)
return self.query(endpoint, params) | [
"def",
"assets",
"(",
"self",
",",
"asset_code",
"=",
"None",
",",
"asset_issuer",
"=",
"None",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/assets'",
"params",
"=",
"self",
".",
"__qu... | This endpoint represents all assets. It will give you all the assets
in the system along with various statistics about each.
See the documentation below for details on query parameters that are
available.
`GET /assets{?asset_code,asset_issuer,cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_
:param str asset_code: Code of the Asset to filter by.
:param str asset_issuer: Issuer of the Asset to filter by.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc",
ordered by asset_code then by asset_issuer.
:param int limit: Maximum number of records to return.
:return: A list of all valid payment operations
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"assets",
".",
"It",
"will",
"give",
"you",
"all",
"the",
"assets",
"in",
"the",
"system",
"along",
"with",
"various",
"statistics",
"about",
"each",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L352-L376 |
248,237 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.transaction | def transaction(self, tx_hash):
"""The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transaction's details.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash)
return self.query(endpoint) | python | def transaction(self, tx_hash):
endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash)
return self.query(endpoint) | [
"def",
"transaction",
"(",
"self",
",",
"tx_hash",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] | The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transaction's details.
:rtype: dict | [
"The",
"transaction",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"transaction",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L399-L412 |
248,238 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.transaction_operations | def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all operations that are part of a given
transaction.
`GET /transactions/{hash}/operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:return: A single transaction's operations.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params) | python | def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10):
endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params) | [
"def",
"transaction_operations",
"(",
"self",
",",
"tx_hash",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"include_failed",
"=",
"False",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}/operations'",
".",
"format"... | This endpoint represents all operations that are part of a given
transaction.
`GET /transactions/{hash}/operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:return: A single transaction's operations.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"operations",
"that",
"are",
"part",
"of",
"a",
"given",
"transaction",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L414-L432 |
248,239 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.transaction_effects | def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A single transaction's effects.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | python | def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):
endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | [
"def",
"transaction_effects",
"(",
"self",
",",
"tx_hash",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}/effects'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
... | This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A single transaction's effects.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"as",
"a",
"result",
"of",
"a",
"given",
"transaction",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L434-L451 |
248,240 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.order_book | def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None,
limit=10):
"""Return, for each orderbook, a summary of the orderbook and the bids
and asks associated with that orderbook.
See the external docs below for information on the arguments required.
`GET /order_book
<https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_
:param str selling_asset_code: Code of the Asset being sold.
:param str buying_asset_code: Type of the Asset being bought.
:param str selling_asset_issuer: Account ID of the issuer of the Asset being sold,
if it is a native asset, let it be `None`.
:param str buying_asset_issuer: Account ID of the issuer of the Asset being bought,
if it is a native asset, let it be `None`.
:param int limit: Limit the number of items returned.
:return: A list of orderbook summaries as a JSON object.
:rtype: dict
"""
selling_asset = Asset(selling_asset_code, selling_asset_issuer)
buying_asset = Asset(buying_asset_code, buying_asset_issuer)
asset_params = {
'selling_asset_type': selling_asset.type,
'selling_asset_code': None if selling_asset.is_native() else selling_asset.code,
'selling_asset_issuer': selling_asset.issuer,
'buying_asset_type': buying_asset.type,
'buying_asset_code': None if buying_asset.is_native() else buying_asset.code,
'buying_asset_issuer': buying_asset.issuer,
}
endpoint = '/order_book'
params = self.__query_params(limit=limit, **asset_params)
return self.query(endpoint, params) | python | def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None,
limit=10):
selling_asset = Asset(selling_asset_code, selling_asset_issuer)
buying_asset = Asset(buying_asset_code, buying_asset_issuer)
asset_params = {
'selling_asset_type': selling_asset.type,
'selling_asset_code': None if selling_asset.is_native() else selling_asset.code,
'selling_asset_issuer': selling_asset.issuer,
'buying_asset_type': buying_asset.type,
'buying_asset_code': None if buying_asset.is_native() else buying_asset.code,
'buying_asset_issuer': buying_asset.issuer,
}
endpoint = '/order_book'
params = self.__query_params(limit=limit, **asset_params)
return self.query(endpoint, params) | [
"def",
"order_book",
"(",
"self",
",",
"selling_asset_code",
",",
"buying_asset_code",
",",
"selling_asset_issuer",
"=",
"None",
",",
"buying_asset_issuer",
"=",
"None",
",",
"limit",
"=",
"10",
")",
":",
"selling_asset",
"=",
"Asset",
"(",
"selling_asset_code",
... | Return, for each orderbook, a summary of the orderbook and the bids
and asks associated with that orderbook.
See the external docs below for information on the arguments required.
`GET /order_book
<https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_
:param str selling_asset_code: Code of the Asset being sold.
:param str buying_asset_code: Type of the Asset being bought.
:param str selling_asset_issuer: Account ID of the issuer of the Asset being sold,
if it is a native asset, let it be `None`.
:param str buying_asset_issuer: Account ID of the issuer of the Asset being bought,
if it is a native asset, let it be `None`.
:param int limit: Limit the number of items returned.
:return: A list of orderbook summaries as a JSON object.
:rtype: dict | [
"Return",
"for",
"each",
"orderbook",
"a",
"summary",
"of",
"the",
"orderbook",
"and",
"the",
"bids",
"and",
"asks",
"associated",
"with",
"that",
"orderbook",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L472-L505 |
248,241 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.ledger | def ledger(self, ledger_id):
"""The ledger details endpoint provides information on a single ledger.
`GET /ledgers/{sequence}
<https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_
:param int ledger_id: The id of the ledger to look up.
:return: The details of a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id)
return self.query(endpoint) | python | def ledger(self, ledger_id):
endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id)
return self.query(endpoint) | [
"def",
"ledger",
"(",
"self",
",",
"ledger_id",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] | The ledger details endpoint provides information on a single ledger.
`GET /ledgers/{sequence}
<https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_
:param int ledger_id: The id of the ledger to look up.
:return: The details of a single ledger.
:rtype: dict | [
"The",
"ledger",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"ledger",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L527-L539 |
248,242 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.ledger_effects | def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred in the given
ledger.
`GET /ledgers/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: The effects for a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | python | def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10):
endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | [
"def",
"ledger_effects",
"(",
"self",
",",
"ledger_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}/effects'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"p... | This endpoint represents all effects that occurred in the given
ledger.
`GET /ledgers/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: The effects for a single ledger.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"in",
"the",
"given",
"ledger",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L541-L558 |
248,243 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.ledger_transactions | def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all transactions in a given ledger.
`GET /ledgers/{id}/transactions{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include failed transactions in results.
:return: The transactions contained in a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/transactions'.format(
ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params) | python | def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10):
endpoint = '/ledgers/{ledger_id}/transactions'.format(
ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params) | [
"def",
"ledger_transactions",
"(",
"self",
",",
"ledger_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"include_failed",
"=",
"False",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}/transactions'",
".",
"format",
... | This endpoint represents all transactions in a given ledger.
`GET /ledgers/{id}/transactions{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include failed transactions in results.
:return: The transactions contained in a single ledger.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"transactions",
"in",
"a",
"given",
"ledger",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L600-L618 |
248,244 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.effects | def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects.
`GET /effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: A list of all effects.
:rtype: dict
"""
endpoint = '/effects'
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse) | python | def effects(self, cursor=None, order='asc', limit=10, sse=False):
endpoint = '/effects'
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse) | [
"def",
"effects",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/effects'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"curs... | This endpoint represents all effects.
`GET /effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: A list of all effects.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"effects",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L620-L638 |
248,245 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.operations | def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False):
"""This endpoint represents all operations that are part of validated
transactions.
`GET /operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:param bool sse: Use server side events for streaming responses.
:return: A list of all operations.
:rtype: dict
"""
endpoint = '/operations'
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params, sse) | python | def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False):
endpoint = '/operations'
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params, sse) | [
"def",
"operations",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"include_failed",
"=",
"False",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/operations'",
"params",
"=",
"self",
".",
... | This endpoint represents all operations that are part of validated
transactions.
`GET /operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:param bool sse: Use server side events for streaming responses.
:return: A list of all operations.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"operations",
"that",
"are",
"part",
"of",
"validated",
"transactions",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L640-L660 |
248,246 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.operation | def operation(self, op_id):
"""The operation details endpoint provides information on a single
operation.
`GET /operations/{id}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_
:param id op_id: The operation ID to get details on.
:return: Details on a single operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}'.format(op_id=op_id)
return self.query(endpoint) | python | def operation(self, op_id):
endpoint = '/operations/{op_id}'.format(op_id=op_id)
return self.query(endpoint) | [
"def",
"operation",
"(",
"self",
",",
"op_id",
")",
":",
"endpoint",
"=",
"'/operations/{op_id}'",
".",
"format",
"(",
"op_id",
"=",
"op_id",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] | The operation details endpoint provides information on a single
operation.
`GET /operations/{id}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_
:param id op_id: The operation ID to get details on.
:return: Details on a single operation.
:rtype: dict | [
"The",
"operation",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"operation",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L662-L674 |
248,247 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.operation_effects | def operation_effects(self, op_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given operation.
`GET /operations/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_
:param int op_id: The operation ID to get effects on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}/effects'.format(op_id=op_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | python | def operation_effects(self, op_id, cursor=None, order='asc', limit=10):
endpoint = '/operations/{op_id}/effects'.format(op_id=op_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | [
"def",
"operation_effects",
"(",
"self",
",",
"op_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/operations/{op_id}/effects'",
".",
"format",
"(",
"op_id",
"=",
"op_id",
")",
"params",
... | This endpoint represents all effects that occurred as a result of a
given operation.
`GET /operations/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_
:param int op_id: The operation ID to get effects on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"as",
"a",
"result",
"of",
"a",
"given",
"operation",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L676-L693 |
248,248 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.paths | def paths(self, destination_account, destination_amount, source_account, destination_asset_code,
destination_asset_issuer=None):
"""Load a list of assets available to the source account id and find
any payment paths from those source assets to the desired
destination asset.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /paths
<https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_
:param str destination_account: The destination account that any returned path should use.
:param str destination_amount: The amount, denominated in the destination asset,
that any returned path should be able to satisfy.
:param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.
:param str destination_asset_code: The asset code for the destination.
:param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.
:type destination_asset_issuer: str, None
:return: A list of paths that can be used to complete a payment based
on a given query.
:rtype: dict
"""
destination_asset = Asset(destination_asset_code, destination_asset_issuer)
destination_asset_params = {
'destination_asset_type': destination_asset.type,
'destination_asset_code': None if destination_asset.is_native() else destination_asset.code,
'destination_asset_issuer': destination_asset.issuer
}
endpoint = '/paths'
params = self.__query_params(destination_account=destination_account,
source_account=source_account,
destination_amount=destination_amount,
**destination_asset_params
)
return self.query(endpoint, params) | python | def paths(self, destination_account, destination_amount, source_account, destination_asset_code,
destination_asset_issuer=None):
destination_asset = Asset(destination_asset_code, destination_asset_issuer)
destination_asset_params = {
'destination_asset_type': destination_asset.type,
'destination_asset_code': None if destination_asset.is_native() else destination_asset.code,
'destination_asset_issuer': destination_asset.issuer
}
endpoint = '/paths'
params = self.__query_params(destination_account=destination_account,
source_account=source_account,
destination_amount=destination_amount,
**destination_asset_params
)
return self.query(endpoint, params) | [
"def",
"paths",
"(",
"self",
",",
"destination_account",
",",
"destination_amount",
",",
"source_account",
",",
"destination_asset_code",
",",
"destination_asset_issuer",
"=",
"None",
")",
":",
"destination_asset",
"=",
"Asset",
"(",
"destination_asset_code",
",",
"de... | Load a list of assets available to the source account id and find
any payment paths from those source assets to the desired
destination asset.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /paths
<https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_
:param str destination_account: The destination account that any returned path should use.
:param str destination_amount: The amount, denominated in the destination asset,
that any returned path should be able to satisfy.
:param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.
:param str destination_asset_code: The asset code for the destination.
:param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.
:type destination_asset_issuer: str, None
:return: A list of paths that can be used to complete a payment based
on a given query.
:rtype: dict | [
"Load",
"a",
"list",
"of",
"assets",
"available",
"to",
"the",
"source",
"account",
"id",
"and",
"find",
"any",
"payment",
"paths",
"from",
"those",
"source",
"assets",
"to",
"the",
"desired",
"destination",
"asset",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L716-L754 |
248,249 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.trades | def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None,
offer_id=None, cursor=None, order='asc', limit=10):
"""Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param int offer_id: Filter for by a specific offer id.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of trades filtered by a given query.
:rtype: dict
"""
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trades'
params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params)
return self.query(endpoint, params) | python | def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None,
offer_id=None, cursor=None, order='asc', limit=10):
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trades'
params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params)
return self.query(endpoint, params) | [
"def",
"trades",
"(",
"self",
",",
"base_asset_code",
"=",
"None",
",",
"counter_asset_code",
"=",
"None",
",",
"base_asset_issuer",
"=",
"None",
",",
"counter_asset_issuer",
"=",
"None",
",",
"offer_id",
"=",
"None",
",",
"cursor",
"=",
"None",
",",
"order"... | Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param int offer_id: Filter for by a specific offer id.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of trades filtered by a given query.
:rtype: dict | [
"Load",
"a",
"list",
"of",
"trades",
"optionally",
"filtered",
"by",
"an",
"orderbook",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L756-L790 |
248,250 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.trade_aggregations | def trade_aggregations(self, resolution, base_asset_code, counter_asset_code,
base_asset_issuer=None, counter_asset_issuer=None, start_time=None,
end_time=None, order='asc', limit=10, offset=0):
"""Load a list of aggregated historical trade data, optionally filtered
by an orderbook.
`GET /trade_aggregations
<https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_
:param int start_time: Lower time boundary represented as millis since epoch.
:param int end_time: Upper time boundary represented as millis since epoch.
:param int resolution: Segment duration as millis since epoch. Supported values
are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000),
1 day (86400000) and 1 week (604800000).
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param int offset: segments can be offset using this parameter.
Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
Value must be in whole hours, less than the provided resolution, and less than 24 hours.
:return: A list of collected trade aggregations.
:rtype: dict
"""
allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000)
if resolution not in allowed_resolutions:
raise NotValidParamError("resolution is invalid")
if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0:
raise NotValidParamError("offset is invalid")
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trade_aggregations'
params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order,
limit=limit, offset=offset, **asset_params)
return self.query(endpoint, params) | python | def trade_aggregations(self, resolution, base_asset_code, counter_asset_code,
base_asset_issuer=None, counter_asset_issuer=None, start_time=None,
end_time=None, order='asc', limit=10, offset=0):
allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000)
if resolution not in allowed_resolutions:
raise NotValidParamError("resolution is invalid")
if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0:
raise NotValidParamError("offset is invalid")
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trade_aggregations'
params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order,
limit=limit, offset=offset, **asset_params)
return self.query(endpoint, params) | [
"def",
"trade_aggregations",
"(",
"self",
",",
"resolution",
",",
"base_asset_code",
",",
"counter_asset_code",
",",
"base_asset_issuer",
"=",
"None",
",",
"counter_asset_issuer",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"o... | Load a list of aggregated historical trade data, optionally filtered
by an orderbook.
`GET /trade_aggregations
<https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_
:param int start_time: Lower time boundary represented as millis since epoch.
:param int end_time: Upper time boundary represented as millis since epoch.
:param int resolution: Segment duration as millis since epoch. Supported values
are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000),
1 day (86400000) and 1 week (604800000).
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param int offset: segments can be offset using this parameter.
Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
Value must be in whole hours, less than the provided resolution, and less than 24 hours.
:return: A list of collected trade aggregations.
:rtype: dict | [
"Load",
"a",
"list",
"of",
"aggregated",
"historical",
"trade",
"data",
"optionally",
"filtered",
"by",
"an",
"orderbook",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L792-L839 |
248,251 | StellarCN/py-stellar-base | stellar_base/horizon.py | Horizon.offer_trades | def offer_trades(self, offer_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | python | def offer_trades(self, offer_id, cursor=None, order='asc', limit=10):
endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params) | [
"def",
"offer_trades",
"(",
"self",
",",
"offer_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/offers/{offer_id}/trades'",
".",
"format",
"(",
"offer_id",
"=",
"offer_id",
")",
"params",
... | This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict | [
"This",
"endpoint",
"represents",
"all",
"trades",
"for",
"a",
"given",
"offer",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L841-L857 |
248,252 | StellarCN/py-stellar-base | stellar_base/transaction_envelope.py | TransactionEnvelope.sign | def sign(self, keypair):
"""Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance's list of
signatures.
:param keypair: The keypair to use for signing this transaction
envelope.
:type keypair: :class:`Keypair <stellar_base.keypair.Keypair>`
:raises: :exc:`SignatureExistError
<stellar_base.utils.SignatureExistError>`
"""
assert isinstance(keypair, Keypair)
tx_hash = self.hash_meta()
sig = keypair.sign_decorated(tx_hash)
sig_dict = [signature.__dict__ for signature in self.signatures]
if sig.__dict__ in sig_dict:
raise SignatureExistError('The keypair has already signed')
else:
self.signatures.append(sig) | python | def sign(self, keypair):
assert isinstance(keypair, Keypair)
tx_hash = self.hash_meta()
sig = keypair.sign_decorated(tx_hash)
sig_dict = [signature.__dict__ for signature in self.signatures]
if sig.__dict__ in sig_dict:
raise SignatureExistError('The keypair has already signed')
else:
self.signatures.append(sig) | [
"def",
"sign",
"(",
"self",
",",
"keypair",
")",
":",
"assert",
"isinstance",
"(",
"keypair",
",",
"Keypair",
")",
"tx_hash",
"=",
"self",
".",
"hash_meta",
"(",
")",
"sig",
"=",
"keypair",
".",
"sign_decorated",
"(",
"tx_hash",
")",
"sig_dict",
"=",
"... | Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance's list of
signatures.
:param keypair: The keypair to use for signing this transaction
envelope.
:type keypair: :class:`Keypair <stellar_base.keypair.Keypair>`
:raises: :exc:`SignatureExistError
<stellar_base.utils.SignatureExistError>` | [
"Sign",
"this",
"transaction",
"envelope",
"with",
"a",
"given",
"keypair",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L43-L63 |
248,253 | StellarCN/py-stellar-base | stellar_base/transaction_envelope.py | TransactionEnvelope.signature_base | def signature_base(self):
"""Get the signature base of this transaction envelope.
Return the "signature base" of this transaction, which is the value
that, when hashed, should be signed to create a signature that
validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of
this transaction.
:return: The signature base of this transaction envelope.
"""
network_id = self.network_id
tx_type = Xdr.StellarXDRPacker()
tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX)
tx_type = tx_type.get_buffer()
tx = Xdr.StellarXDRPacker()
tx.pack_Transaction(self.tx.to_xdr_object())
tx = tx.get_buffer()
return network_id + tx_type + tx | python | def signature_base(self):
network_id = self.network_id
tx_type = Xdr.StellarXDRPacker()
tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX)
tx_type = tx_type.get_buffer()
tx = Xdr.StellarXDRPacker()
tx.pack_Transaction(self.tx.to_xdr_object())
tx = tx.get_buffer()
return network_id + tx_type + tx | [
"def",
"signature_base",
"(",
"self",
")",
":",
"network_id",
"=",
"self",
".",
"network_id",
"tx_type",
"=",
"Xdr",
".",
"StellarXDRPacker",
"(",
")",
"tx_type",
".",
"pack_EnvelopeType",
"(",
"Xdr",
".",
"const",
".",
"ENVELOPE_TYPE_TX",
")",
"tx_type",
"=... | Get the signature base of this transaction envelope.
Return the "signature base" of this transaction, which is the value
that, when hashed, should be signed to create a signature that
validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of
this transaction.
:return: The signature base of this transaction envelope. | [
"Get",
"the",
"signature",
"base",
"of",
"this",
"transaction",
"envelope",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L99-L120 |
248,254 | StellarCN/py-stellar-base | stellar_base/federation.py | get_federation_service | def get_federation_service(domain, allow_http=False):
"""Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The FEDERATION_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('FEDERATION_SERVER') | python | def get_federation_service(domain, allow_http=False):
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('FEDERATION_SERVER') | [
"def",
"get_federation_service",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"st",
"=",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
")",
"if",
"not",
"st",
":",
"return",
"None",
"return",
"st",
".",
"get",
"(",
"'FEDERATION_SERVER'",... | Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The FEDERATION_SERVER url. | [
"Retrieve",
"the",
"FEDERATION_SERVER",
"config",
"from",
"a",
"domain",
"s",
"stellar",
".",
"toml",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L76-L88 |
248,255 | StellarCN/py-stellar-base | stellar_base/federation.py | get_auth_server | def get_auth_server(domain, allow_http=False):
"""Retrieve the AUTH_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The AUTH_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('AUTH_SERVER') | python | def get_auth_server(domain, allow_http=False):
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('AUTH_SERVER') | [
"def",
"get_auth_server",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"st",
"=",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
")",
"if",
"not",
"st",
":",
"return",
"None",
"return",
"st",
".",
"get",
"(",
"'AUTH_SERVER'",
")"
] | Retrieve the AUTH_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The AUTH_SERVER url. | [
"Retrieve",
"the",
"AUTH_SERVER",
"config",
"from",
"a",
"domain",
"s",
"stellar",
".",
"toml",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L91-L103 |
248,256 | StellarCN/py-stellar-base | stellar_base/federation.py | get_stellar_toml | def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return: The stellar.toml file as a an object via :func:`toml.loads`.
"""
toml_link = '/.well-known/stellar.toml'
if allow_http:
protocol = 'http://'
else:
protocol = 'https://'
url_list = ['', 'www.', 'stellar.']
url_list = [protocol + url + domain + toml_link for url in url_list]
for url in url_list:
r = requests.get(url)
if r.status_code == 200:
return toml.loads(r.text)
return None | python | def get_stellar_toml(domain, allow_http=False):
toml_link = '/.well-known/stellar.toml'
if allow_http:
protocol = 'http://'
else:
protocol = 'https://'
url_list = ['', 'www.', 'stellar.']
url_list = [protocol + url + domain + toml_link for url in url_list]
for url in url_list:
r = requests.get(url)
if r.status_code == 200:
return toml.loads(r.text)
return None | [
"def",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"toml_link",
"=",
"'/.well-known/stellar.toml'",
"if",
"allow_http",
":",
"protocol",
"=",
"'http://'",
"else",
":",
"protocol",
"=",
"'https://'",
"url_list",
"=",
"[",
"''",
... | Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return: The stellar.toml file as a an object via :func:`toml.loads`. | [
"Retrieve",
"the",
"stellar",
".",
"toml",
"file",
"from",
"a",
"given",
"domain",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L106-L132 |
248,257 | StellarCN/py-stellar-base | stellar_base/keypair.py | Keypair.account_xdr_object | def account_xdr_object(self):
"""Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
"""
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes()) | python | def account_xdr_object(self):
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes()) | [
"def",
"account_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"PublicKey",
"(",
"Xdr",
".",
"const",
".",
"KEY_TYPE_ED25519",
",",
"self",
".",
"verifying_key",
".",
"to_bytes",
"(",
")",
")"
] | Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type. | [
"Create",
"PublicKey",
"XDR",
"object",
"via",
"public",
"key",
"bytes",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L154-L160 |
248,258 | StellarCN/py-stellar-base | stellar_base/keypair.py | Keypair.xdr | def xdr(self):
"""Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
"""
kp = Xdr.StellarXDRPacker()
kp.pack_PublicKey(self.account_xdr_object())
return base64.b64encode(kp.get_buffer()) | python | def xdr(self):
kp = Xdr.StellarXDRPacker()
kp.pack_PublicKey(self.account_xdr_object())
return base64.b64encode(kp.get_buffer()) | [
"def",
"xdr",
"(",
"self",
")",
":",
"kp",
"=",
"Xdr",
".",
"StellarXDRPacker",
"(",
")",
"kp",
".",
"pack_PublicKey",
"(",
"self",
".",
"account_xdr_object",
"(",
")",
")",
"return",
"base64",
".",
"b64encode",
"(",
"kp",
".",
"get_buffer",
"(",
")",
... | Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure. | [
"Generate",
"base64",
"encoded",
"XDR",
"PublicKey",
"object",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L162-L172 |
248,259 | StellarCN/py-stellar-base | stellar_base/keypair.py | Keypair.verify | def verify(self, data, signature):
"""Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
"""
try:
return self.verifying_key.verify(signature, data)
except ed25519.BadSignatureError:
raise BadSignatureError("Signature verification failed.") | python | def verify(self, data, signature):
try:
return self.verifying_key.verify(signature, data)
except ed25519.BadSignatureError:
raise BadSignatureError("Signature verification failed.") | [
"def",
"verify",
"(",
"self",
",",
"data",
",",
"signature",
")",
":",
"try",
":",
"return",
"self",
".",
"verifying_key",
".",
"verify",
"(",
"signature",
",",
"data",
")",
"except",
"ed25519",
".",
"BadSignatureError",
":",
"raise",
"BadSignatureError",
... | Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data. | [
"Verify",
"the",
"signature",
"of",
"a",
"sequence",
"of",
"bytes",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L228-L243 |
248,260 | StellarCN/py-stellar-base | stellar_base/keypair.py | Keypair.sign_decorated | def sign_decorated(self, data):
"""Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
"""
signature = self.sign(data)
hint = self.signature_hint()
return Xdr.types.DecoratedSignature(hint, signature) | python | def sign_decorated(self, data):
signature = self.sign(data)
hint = self.signature_hint()
return Xdr.types.DecoratedSignature(hint, signature) | [
"def",
"sign_decorated",
"(",
"self",
",",
"data",
")",
":",
"signature",
"=",
"self",
".",
"sign",
"(",
"data",
")",
"hint",
"=",
"self",
".",
"signature_hint",
"(",
")",
"return",
"Xdr",
".",
"types",
".",
"DecoratedSignature",
"(",
"hint",
",",
"sig... | Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction. | [
"Sign",
"a",
"bytes",
"-",
"like",
"object",
"and",
"return",
"the",
"decorated",
"signature",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L245-L259 |
248,261 | StellarCN/py-stellar-base | stellar_base/utils.py | bytes_from_decode_data | def bytes_from_decode_data(s):
"""copy from base64._bytes_from_decode_data
"""
if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
raise NotValidParamError(
'String argument should contain only ASCII characters')
if isinstance(s, bytes_types):
return s
try:
return memoryview(s).tobytes()
except TypeError:
raise suppress_context(
TypeError(
'Argument should be a bytes-like object or ASCII string, not '
'{!r}'.format(s.__class__.__name__))) | python | def bytes_from_decode_data(s):
if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
raise NotValidParamError(
'String argument should contain only ASCII characters')
if isinstance(s, bytes_types):
return s
try:
return memoryview(s).tobytes()
except TypeError:
raise suppress_context(
TypeError(
'Argument should be a bytes-like object or ASCII string, not '
'{!r}'.format(s.__class__.__name__))) | [
"def",
"bytes_from_decode_data",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"try",
":",
"return",
"s",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"raise",
"NotValidParam... | copy from base64._bytes_from_decode_data | [
"copy",
"from",
"base64",
".",
"_bytes_from_decode_data"
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/utils.py#L75-L92 |
248,262 | StellarCN/py-stellar-base | stellar_base/operation.py | Operation.to_xdr_amount | def to_xdr_amount(value):
"""Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
"""
if not isinstance(value, str):
raise NotValidParamError("Value of type '{}' must be of type String, but got {}".format(value, type(value)))
# throw exception if value * ONE has decimal places (it can't be
# represented as int64)
try:
amount = int((Decimal(value) * ONE).to_integral_exact(context=Context(traps=[Inexact])))
except decimal.Inexact:
raise NotValidParamError("Value of '{}' must have at most 7 digits after the decimal.".format(value))
except decimal.InvalidOperation:
raise NotValidParamError("Value of '{}' must represent a positive number.".format(value))
return amount | python | def to_xdr_amount(value):
if not isinstance(value, str):
raise NotValidParamError("Value of type '{}' must be of type String, but got {}".format(value, type(value)))
# throw exception if value * ONE has decimal places (it can't be
# represented as int64)
try:
amount = int((Decimal(value) * ONE).to_integral_exact(context=Context(traps=[Inexact])))
except decimal.Inexact:
raise NotValidParamError("Value of '{}' must have at most 7 digits after the decimal.".format(value))
except decimal.InvalidOperation:
raise NotValidParamError("Value of '{}' must represent a positive number.".format(value))
return amount | [
"def",
"to_xdr_amount",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"NotValidParamError",
"(",
"\"Value of type '{}' must be of type String, but got {}\"",
".",
"format",
"(",
"value",
",",
"type",
"(",
"value",
... | Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization. | [
"Converts",
"an",
"amount",
"to",
"the",
"appropriate",
"value",
"to",
"send",
"over",
"the",
"network",
"as",
"a",
"part",
"of",
"an",
"XDR",
"object",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/operation.py#L71-L105 |
248,263 | StellarCN/py-stellar-base | stellar_base/memo.py | TextMemo.to_xdr_object | def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_TEXT."""
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text) | python | def to_xdr_object(self):
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text) | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_TEXT",
",",
"text",
"=",
"self",
".",
"text",
")"
] | Creates an XDR Memo object for a transaction with MEMO_TEXT. | [
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_TEXT",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L97-L99 |
248,264 | StellarCN/py-stellar-base | stellar_base/memo.py | IdMemo.to_xdr_object | def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_ID."""
return Xdr.types.Memo(type=Xdr.const.MEMO_ID, id=self.memo_id) | python | def to_xdr_object(self):
return Xdr.types.Memo(type=Xdr.const.MEMO_ID, id=self.memo_id) | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_ID",
",",
"id",
"=",
"self",
".",
"memo_id",
")"
] | Creates an XDR Memo object for a transaction with MEMO_ID. | [
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_ID",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L112-L114 |
248,265 | StellarCN/py-stellar-base | stellar_base/memo.py | HashMemo.to_xdr_object | def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_HASH."""
return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash) | python | def to_xdr_object(self):
return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash) | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_HASH",
",",
"hash",
"=",
"self",
".",
"memo_hash",
")"
] | Creates an XDR Memo object for a transaction with MEMO_HASH. | [
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_HASH",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L127-L129 |
248,266 | StellarCN/py-stellar-base | stellar_base/memo.py | RetHashMemo.to_xdr_object | def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_RETURN."""
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return) | python | def to_xdr_object(self):
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return) | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_RETURN",
",",
"retHash",
"=",
"self",
".",
"memo_return",
")"
] | Creates an XDR Memo object for a transaction with MEMO_RETURN. | [
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_RETURN",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L148-L151 |
248,267 | StellarCN/py-stellar-base | stellar_base/builder.py | Builder.append_hashx_signer | def append_hashx_signer(self, hashx, signer_weight, source=None):
"""Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=hashx,
signer_type='hashX',
signer_weight=signer_weight,
source=source) | python | def append_hashx_signer(self, hashx, signer_weight, source=None):
return self.append_set_options_op(
signer_address=hashx,
signer_type='hashX',
signer_weight=signer_weight,
source=source) | [
"def",
"append_hashx_signer",
"(",
"self",
",",
"hashx",
",",
"signer_weight",
",",
"source",
"=",
"None",
")",
":",
"return",
"self",
".",
"append_set_options_op",
"(",
"signer_address",
"=",
"hashx",
",",
"signer_type",
"=",
"'hashX'",
",",
"signer_weight",
... | Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance. | [
"Add",
"a",
"HashX",
"signer",
"to",
"an",
"account",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L323-L342 |
248,268 | StellarCN/py-stellar-base | stellar_base/builder.py | Builder.append_pre_auth_tx_signer | def append_pre_auth_tx_signer(self,
pre_auth_tx,
signer_weight,
source=None):
"""Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=pre_auth_tx,
signer_type='preAuthTx',
signer_weight=signer_weight,
source=source) | python | def append_pre_auth_tx_signer(self,
pre_auth_tx,
signer_weight,
source=None):
return self.append_set_options_op(
signer_address=pre_auth_tx,
signer_type='preAuthTx',
signer_weight=signer_weight,
source=source) | [
"def",
"append_pre_auth_tx_signer",
"(",
"self",
",",
"pre_auth_tx",
",",
"signer_weight",
",",
"source",
"=",
"None",
")",
":",
"return",
"self",
".",
"append_set_options_op",
"(",
"signer_address",
"=",
"pre_auth_tx",
",",
"signer_type",
"=",
"'preAuthTx'",
",",... | Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance. | [
"Add",
"a",
"PreAuthTx",
"signer",
"to",
"an",
"account",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L344-L366 |
248,269 | StellarCN/py-stellar-base | stellar_base/builder.py | Builder.next_builder | def next_builder(self):
"""Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
"""
sequence = self.sequence + 1
next_builder = Builder(
horizon_uri=self.horizon.horizon_uri,
address=self.address,
network=self.network,
sequence=sequence,
fee=self.fee)
next_builder.keypair = self.keypair
return next_builder | python | def next_builder(self):
sequence = self.sequence + 1
next_builder = Builder(
horizon_uri=self.horizon.horizon_uri,
address=self.address,
network=self.network,
sequence=sequence,
fee=self.fee)
next_builder.keypair = self.keypair
return next_builder | [
"def",
"next_builder",
"(",
"self",
")",
":",
"sequence",
"=",
"self",
".",
"sequence",
"+",
"1",
"next_builder",
"=",
"Builder",
"(",
"horizon_uri",
"=",
"self",
".",
"horizon",
".",
"horizon_uri",
",",
"address",
"=",
"self",
".",
"address",
",",
"netw... | Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder` | [
"Create",
"a",
"new",
"builder",
"based",
"off",
"of",
"this",
"one",
"with",
"its",
"sequence",
"number",
"incremented",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L786-L802 |
248,270 | StellarCN/py-stellar-base | stellar_base/builder.py | Builder.get_sequence | def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.account(self.address)
return int(address.get('sequence')) | python | def get_sequence(self):
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.account(self.address)
return int(address.get('sequence')) | [
"def",
"get_sequence",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"address",
":",
"raise",
"StellarAddressInvalidError",
"(",
"'No address provided.'",
")",
"address",
"=",
"self",
".",
"horizon",
".",
"account",
"(",
"self",
".",
"address",
")",
"retu... | Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int | [
"Get",
"the",
"sequence",
"number",
"for",
"a",
"given",
"account",
"via",
"Horizon",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L804-L814 |
248,271 | StellarCN/py-stellar-base | stellar_base/asset.py | Asset.to_dict | def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
"""
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type'] = 'native'
return rv | python | def to_dict(self):
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type'] = 'native'
return rv | [
"def",
"to_dict",
"(",
"self",
")",
":",
"rv",
"=",
"{",
"'code'",
":",
"self",
".",
"code",
"}",
"if",
"not",
"self",
".",
"is_native",
"(",
")",
":",
"rv",
"[",
"'issuer'",
"]",
"=",
"self",
".",
"issuer",
"rv",
"[",
"'type'",
"]",
"=",
"self... | Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset` | [
"Generate",
"a",
"dict",
"for",
"this",
"object",
"s",
"attributes",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/asset.py#L61-L72 |
248,272 | StellarCN/py-stellar-base | stellar_base/stellarxdr/xdrgen.py | id_unique | def id_unique(dict_id, name, lineno):
"""Returns True if dict_id not already used. Otherwise, invokes error"""
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(name, dict_id, lineno, name_dict[dict_id]))
return False
else:
return True | python | def id_unique(dict_id, name, lineno):
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(name, dict_id, lineno, name_dict[dict_id]))
return False
else:
return True | [
"def",
"id_unique",
"(",
"dict_id",
",",
"name",
",",
"lineno",
")",
":",
"if",
"dict_id",
"in",
"name_dict",
":",
"global",
"error_occurred",
"error_occurred",
"=",
"True",
"print",
"(",
"\"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}\"",
".",
"f... | Returns True if dict_id not already used. Otherwise, invokes error | [
"Returns",
"True",
"if",
"dict_id",
"not",
"already",
"used",
".",
"Otherwise",
"invokes",
"error"
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/stellarxdr/xdrgen.py#L770-L780 |
248,273 | StellarCN/py-stellar-base | stellar_base/base58.py | main | def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode', action='store_true', help='decode data')
parser.add_argument(
'-c',
'--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read().rstrip(b'\n')
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result) | python | def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode', action='store_true', help='decode data')
parser.add_argument(
'-c',
'--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read().rstrip(b'\n')
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result) | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
"import",
"argparse",
"stdout",
"=",
"buffer",
"(",
"sys",
".",
"stdout",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argu... | Base58 encode or decode FILE, or standard input, to standard output. | [
"Base58",
"encode",
"or",
"decode",
"FILE",
"or",
"standard",
"input",
"to",
"standard",
"output",
"."
] | cce2e782064fb3955c85e1696e630d67b1010848 | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/base58.py#L93-L134 |
248,274 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_11/utils.py | Utils._Dhcpcd | def _Dhcpcd(self, interfaces, logger):
"""Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
subprocess.check_call(dhcpcd + ['-x', interface])
except subprocess.CalledProcessError:
# Dhcpcd not yet running for this device.
logger.info('Dhcpcd not yet running for interface %s.', interface)
try:
subprocess.check_call(dhcpcd + [interface])
except subprocess.CalledProcessError:
# The interface is already active.
logger.warning('Could not activate interface %s.', interface) | python | def _Dhcpcd(self, interfaces, logger):
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
subprocess.check_call(dhcpcd + ['-x', interface])
except subprocess.CalledProcessError:
# Dhcpcd not yet running for this device.
logger.info('Dhcpcd not yet running for interface %s.', interface)
try:
subprocess.check_call(dhcpcd + [interface])
except subprocess.CalledProcessError:
# The interface is already active.
logger.warning('Could not activate interface %s.', interface) | [
"def",
"_Dhcpcd",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"dhcpcd",
"=",
"[",
"'/sbin/dhcpcd'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhcpcd",
"+",
"[",
"'-x'",
",",
"interfa... | Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port. | [
"Use",
"dhcpcd",
"to",
"activate",
"the",
"interfaces",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_11/utils.py#L44-L62 |
248,275 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py | _CreateTempDir | def _CreateTempDir(prefix, run_dir=None):
"""Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
"""
temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir) | python | def _CreateTempDir(prefix, run_dir=None):
temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir) | [
"def",
"_CreateTempDir",
"(",
"prefix",
",",
"run_dir",
"=",
"None",
")",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"prefix",
"+",
"'-'",
",",
"dir",
"=",
"run_dir",
")",
"try",
":",
"yield",
"temp_dir",
"finally",
":",
"shu... | Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created. | [
"Context",
"manager",
"for",
"creating",
"a",
"temporary",
"directory",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py#L31-L45 |
248,276 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py | ScriptManager._RunScripts | def _RunScripts(self, run_dir=None):
"""Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
"""
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', self.script_type)
script_dict = self.retriever.GetScripts(dest_dir)
self.executor.RunScripts(script_dict)
finally:
self.logger.info('Finished running %s scripts.', self.script_type) | python | def _RunScripts(self, run_dir=None):
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', self.script_type)
script_dict = self.retriever.GetScripts(dest_dir)
self.executor.RunScripts(script_dict)
finally:
self.logger.info('Finished running %s scripts.', self.script_type) | [
"def",
"_RunScripts",
"(",
"self",
",",
"run_dir",
"=",
"None",
")",
":",
"with",
"_CreateTempDir",
"(",
"self",
".",
"script_type",
",",
"run_dir",
"=",
"run_dir",
")",
"as",
"dest_dir",
":",
"try",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Star... | Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory. | [
"Retrieve",
"metadata",
"scripts",
"and",
"execute",
"them",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py#L71-L83 |
248,277 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py | InstanceSetup._GetInstanceConfig | def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = self.metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return (instance_data.get('google-instance-configs')
or project_data.get('google-instance-configs')) | python | def _GetInstanceConfig(self):
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = self.metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return (instance_data.get('google-instance-configs')
or project_data.get('google-instance-configs')) | [
"def",
"_GetInstanceConfig",
"(",
"self",
")",
":",
"try",
":",
"instance_data",
"=",
"self",
".",
"metadata_dict",
"[",
"'instance'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"instance_data",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"wa... | Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data. | [
"Get",
"the",
"instance",
"configuration",
"specified",
"in",
"metadata",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L72-L91 |
248,278 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py | InstanceSetup._GenerateSshKey | def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
temp_key = temp.name
command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
try:
self.logger.info('Generating SSH key %s.', key_dest)
subprocess.check_call(command)
except subprocess.CalledProcessError:
self.logger.warning('Could not create SSH key %s.', key_dest)
return
shutil.move(temp_key, key_dest)
shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)
file_utils.SetPermissions(key_dest, mode=0o600)
file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644) | python | def _GenerateSshKey(self, key_type, key_dest):
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
temp_key = temp.name
command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
try:
self.logger.info('Generating SSH key %s.', key_dest)
subprocess.check_call(command)
except subprocess.CalledProcessError:
self.logger.warning('Could not create SSH key %s.', key_dest)
return
shutil.move(temp_key, key_dest)
shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)
file_utils.SetPermissions(key_dest, mode=0o600)
file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644) | [
"def",
"_GenerateSshKey",
"(",
"self",
",",
"key_type",
",",
"key_dest",
")",
":",
"# Create a temporary file to save the created RSA keys.",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"key_type",
",",
"delete",
"=",
"True",
")",
"as",
"temp"... | Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key. | [
"Generate",
"a",
"new",
"SSH",
"key",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L119-L142 |
248,279 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py | InstanceSetup._StartSshd | def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.conf')):
subprocess.call(['service', 'ssh', 'start'])
subprocess.call(['service', 'ssh', 'reload'])
elif (os.path.exists('/etc/init.d/sshd')
or os.path.exists('/etc/init/sshd.conf')):
subprocess.call(['service', 'sshd', 'start'])
subprocess.call(['service', 'sshd', 'reload']) | python | def _StartSshd(self):
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.conf')):
subprocess.call(['service', 'ssh', 'start'])
subprocess.call(['service', 'ssh', 'reload'])
elif (os.path.exists('/etc/init.d/sshd')
or os.path.exists('/etc/init/sshd.conf')):
subprocess.call(['service', 'sshd', 'start'])
subprocess.call(['service', 'sshd', 'reload']) | [
"def",
"_StartSshd",
"(",
"self",
")",
":",
"# Exit as early as possible.",
"# Instance setup systemd scripts block sshd from starting.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"LOCALBASE",
"+",
"'/bin/systemctl'",
")",
":",
"return",
"elif",
"... | Initialize the SSH daemon. | [
"Initialize",
"the",
"SSH",
"daemon",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L144-L157 |
248,280 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py | InstanceSetup._SetSshHostKeys | def _SetSshHostKeys(self, host_key_types=None):
"""Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first time the instance is booted, and each time
the disk is used to boot a new instance.
Args:
host_key_types: string, a comma separated list of host key types.
"""
section = 'Instance'
instance_id = self._GetInstanceId()
if instance_id != self.instance_config.GetOptionString(
section, 'instance_id'):
self.logger.info('Generating SSH host keys for instance %s.', instance_id)
file_regex = re.compile(r'ssh_host_(?P<type>[a-z0-9]*)_key\Z')
key_dir = '/etc/ssh'
key_files = [f for f in os.listdir(key_dir) if file_regex.match(f)]
key_types = host_key_types.split(',') if host_key_types else []
key_types_files = ['ssh_host_%s_key' % key_type for key_type in key_types]
for key_file in set(key_files) | set(key_types_files):
key_type = file_regex.match(key_file).group('type')
key_dest = os.path.join(key_dir, key_file)
self._GenerateSshKey(key_type, key_dest)
self._StartSshd()
self.instance_config.SetOption(section, 'instance_id', str(instance_id)) | python | def _SetSshHostKeys(self, host_key_types=None):
section = 'Instance'
instance_id = self._GetInstanceId()
if instance_id != self.instance_config.GetOptionString(
section, 'instance_id'):
self.logger.info('Generating SSH host keys for instance %s.', instance_id)
file_regex = re.compile(r'ssh_host_(?P<type>[a-z0-9]*)_key\Z')
key_dir = '/etc/ssh'
key_files = [f for f in os.listdir(key_dir) if file_regex.match(f)]
key_types = host_key_types.split(',') if host_key_types else []
key_types_files = ['ssh_host_%s_key' % key_type for key_type in key_types]
for key_file in set(key_files) | set(key_types_files):
key_type = file_regex.match(key_file).group('type')
key_dest = os.path.join(key_dir, key_file)
self._GenerateSshKey(key_type, key_dest)
self._StartSshd()
self.instance_config.SetOption(section, 'instance_id', str(instance_id)) | [
"def",
"_SetSshHostKeys",
"(",
"self",
",",
"host_key_types",
"=",
"None",
")",
":",
"section",
"=",
"'Instance'",
"instance_id",
"=",
"self",
".",
"_GetInstanceId",
"(",
")",
"if",
"instance_id",
"!=",
"self",
".",
"instance_config",
".",
"GetOptionString",
"... | Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first time the instance is booted, and each time
the disk is used to boot a new instance.
Args:
host_key_types: string, a comma separated list of host key types. | [
"Regenerates",
"SSH",
"host",
"keys",
"when",
"the",
"VM",
"is",
"restarted",
"with",
"a",
"new",
"IP",
"address",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L159-L185 |
248,281 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py | InstanceSetup._SetupBotoConfig | def _SetupBotoConfig(self):
"""Set the boto config so GSUtil works with provisioned service accounts."""
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e)) | python | def _SetupBotoConfig(self):
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e)) | [
"def",
"_SetupBotoConfig",
"(",
"self",
")",
":",
"project_id",
"=",
"self",
".",
"_GetNumericProjectId",
"(",
")",
"try",
":",
"boto_config",
".",
"BotoConfig",
"(",
"project_id",
",",
"debug",
"=",
"self",
".",
"debug",
")",
"except",
"(",
"IOError",
","... | Set the boto config so GSUtil works with provisioned service accounts. | [
"Set",
"the",
"boto",
"config",
"so",
"GSUtil",
"works",
"with",
"provisioned",
"service",
"accounts",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L199-L205 |
248,282 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | ScriptRetriever._DownloadAuthUrl | def _DownloadAuthUrl(self, url, dest_dir):
"""Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info(
'Downloading url from %s to %s using authentication token.', url, dest)
if not self.token:
response = self.watcher.GetMetadata(
self.token_metadata_key, recursive=False, retry=False)
if not response:
self.logger.info(
'Authentication token not found. Attempting unauthenticated '
'download.')
return self._DownloadUrl(url, dest_dir)
self.token = '%s %s' % (
response.get('token_type', ''), response.get('access_token', ''))
try:
request = urlrequest.Request(url)
request.add_unredirected_header('Metadata-Flavor', 'Google')
request.add_unredirected_header('Authorization', self.token)
content = urlrequest.urlopen(request).read().decode('utf-8')
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
return None
with open(dest, 'wb') as f:
f.write(content)
return dest | python | def _DownloadAuthUrl(self, url, dest_dir):
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info(
'Downloading url from %s to %s using authentication token.', url, dest)
if not self.token:
response = self.watcher.GetMetadata(
self.token_metadata_key, recursive=False, retry=False)
if not response:
self.logger.info(
'Authentication token not found. Attempting unauthenticated '
'download.')
return self._DownloadUrl(url, dest_dir)
self.token = '%s %s' % (
response.get('token_type', ''), response.get('access_token', ''))
try:
request = urlrequest.Request(url)
request.add_unredirected_header('Metadata-Flavor', 'Google')
request.add_unredirected_header('Authorization', self.token)
content = urlrequest.urlopen(request).read().decode('utf-8')
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
return None
with open(dest, 'wb') as f:
f.write(content)
return dest | [
"def",
"_DownloadAuthUrl",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"dest_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"dest_dir",
",",
"delete",
"=",
"False",
")",
"dest_file",
".",
"close",
"(",
")",
"dest",
"=",
"dest... | Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script. | [
"Download",
"a",
"Google",
"Storage",
"URL",
"using",
"an",
"authentication",
"token",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L48-L92 |
248,283 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | ScriptRetriever._DownloadUrl | def _DownloadUrl(self, url, dest_dir):
"""Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info('Downloading url from %s to %s.', url, dest)
try:
urlretrieve.urlretrieve(url, dest)
return dest
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
except Exception as e:
self.logger.warning('Exception downloading %s. %s.', url, str(e))
return None | python | def _DownloadUrl(self, url, dest_dir):
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info('Downloading url from %s to %s.', url, dest)
try:
urlretrieve.urlretrieve(url, dest)
return dest
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
except Exception as e:
self.logger.warning('Exception downloading %s. %s.', url, str(e))
return None | [
"def",
"_DownloadUrl",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"dest_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"dest_dir",
",",
"delete",
"=",
"False",
")",
"dest_file",
".",
"close",
"(",
")",
"dest",
"=",
"dest_fil... | Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script. | [
"Download",
"a",
"script",
"from",
"a",
"given",
"URL",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L94-L116 |
248,284 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | ScriptRetriever._DownloadScript | def _DownloadScript(self, url, dest_dir):
"""Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
# Check for the preferred Google Storage URL format:
# gs://<bucket>/<object>
if url.startswith(r'gs://'):
# Convert the string into a standard URL.
url = re.sub('^gs://', 'https://storage.googleapis.com/', url)
return self._DownloadAuthUrl(url, dest_dir)
header = r'http[s]?://'
domain = r'storage\.googleapis\.com'
# Many of the Google Storage URLs are supported below.
# It is prefered that customers specify their object using
# its gs://<bucket>/<object> url.
bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'
# Accept any non-empty string that doesn't contain a wildcard character
obj = r'(?P<obj>[^\*\?]+)'
# Check for the Google Storage URLs:
# http://<bucket>.storage.googleapis.com/<object>
# https://<bucket>.storage.googleapis.com/<object>
gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Check for the other possible Google Storage URLs:
# http://storage.googleapis.com/<bucket>/<object>
# https://storage.googleapis.com/<bucket>/<object>
#
# The following are deprecated but checked:
# http://commondatastorage.googleapis.com/<bucket>/<object>
# https://commondatastorage.googleapis.com/<bucket>/<object>
gs_regex = re.compile(
r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Unauthenticated download of the object.
return self._DownloadUrl(url, dest_dir) | python | def _DownloadScript(self, url, dest_dir):
# Check for the preferred Google Storage URL format:
# gs://<bucket>/<object>
if url.startswith(r'gs://'):
# Convert the string into a standard URL.
url = re.sub('^gs://', 'https://storage.googleapis.com/', url)
return self._DownloadAuthUrl(url, dest_dir)
header = r'http[s]?://'
domain = r'storage\.googleapis\.com'
# Many of the Google Storage URLs are supported below.
# It is prefered that customers specify their object using
# its gs://<bucket>/<object> url.
bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'
# Accept any non-empty string that doesn't contain a wildcard character
obj = r'(?P<obj>[^\*\?]+)'
# Check for the Google Storage URLs:
# http://<bucket>.storage.googleapis.com/<object>
# https://<bucket>.storage.googleapis.com/<object>
gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Check for the other possible Google Storage URLs:
# http://storage.googleapis.com/<bucket>/<object>
# https://storage.googleapis.com/<bucket>/<object>
#
# The following are deprecated but checked:
# http://commondatastorage.googleapis.com/<bucket>/<object>
# https://commondatastorage.googleapis.com/<bucket>/<object>
gs_regex = re.compile(
r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Unauthenticated download of the object.
return self._DownloadUrl(url, dest_dir) | [
"def",
"_DownloadScript",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"# Check for the preferred Google Storage URL format:",
"# gs://<bucket>/<object>",
"if",
"url",
".",
"startswith",
"(",
"r'gs://'",
")",
":",
"# Convert the string into a standard URL.",
"url",
... | Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script. | [
"Download",
"the",
"contents",
"of",
"the",
"URL",
"to",
"the",
"destination",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L118-L168 |
248,285 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | ScriptRetriever._GetAttributeScripts | def _GetAttributeScripts(self, attribute_data, dest_dir):
"""Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts.
"""
script_dict = {}
attribute_data = attribute_data or {}
metadata_key = '%s-script' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
with tempfile.NamedTemporaryFile(
mode='w', dir=dest_dir, delete=False) as dest:
dest.write(metadata_value.lstrip())
script_dict[metadata_key] = dest.name
metadata_key = '%s-script-url' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
script_dict[metadata_key] = self._DownloadScript(
metadata_value, dest_dir)
return script_dict | python | def _GetAttributeScripts(self, attribute_data, dest_dir):
script_dict = {}
attribute_data = attribute_data or {}
metadata_key = '%s-script' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
with tempfile.NamedTemporaryFile(
mode='w', dir=dest_dir, delete=False) as dest:
dest.write(metadata_value.lstrip())
script_dict[metadata_key] = dest.name
metadata_key = '%s-script-url' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
script_dict[metadata_key] = self._DownloadScript(
metadata_value, dest_dir)
return script_dict | [
"def",
"_GetAttributeScripts",
"(",
"self",
",",
"attribute_data",
",",
"dest_dir",
")",
":",
"script_dict",
"=",
"{",
"}",
"attribute_data",
"=",
"attribute_data",
"or",
"{",
"}",
"metadata_key",
"=",
"'%s-script'",
"%",
"self",
".",
"script_type",
"metadata_va... | Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts. | [
"Retrieve",
"the",
"scripts",
"from",
"attribute",
"metadata",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L170-L198 |
248,286 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | ScriptRetriever.GetScripts | def GetScripts(self, dest_dir):
"""Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts.
"""
metadata_dict = self.watcher.GetMetadata() or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = None
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = None
self.logger.warning('Project attributes were not found.')
return (self._GetAttributeScripts(instance_data, dest_dir)
or self._GetAttributeScripts(project_data, dest_dir)) | python | def GetScripts(self, dest_dir):
metadata_dict = self.watcher.GetMetadata() or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = None
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = None
self.logger.warning('Project attributes were not found.')
return (self._GetAttributeScripts(instance_data, dest_dir)
or self._GetAttributeScripts(project_data, dest_dir)) | [
"def",
"GetScripts",
"(",
"self",
",",
"dest_dir",
")",
":",
"metadata_dict",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
")",
"or",
"{",
"}",
"try",
":",
"instance_data",
"=",
"metadata_dict",
"[",
"'instance'",
"]",
"[",
"'attributes'",
"]",
... | Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts. | [
"Retrieve",
"the",
"scripts",
"to",
"execute",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L200-L224 |
248,287 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py | ScriptExecutor._MakeExecutable | def _MakeExecutable(self, metadata_script):
"""Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
"""
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC) | python | def _MakeExecutable(self, metadata_script):
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC) | [
"def",
"_MakeExecutable",
"(",
"self",
",",
"metadata_script",
")",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"metadata_script",
")",
".",
"st_mode",
"os",
".",
"chmod",
"(",
"metadata_script",
",",
"mode",
"|",
"stat",
".",
"S_IEXEC",
")"
] | Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file. | [
"Add",
"executable",
"permissions",
"to",
"a",
"file",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py#L38-L45 |
248,288 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py | ScriptExecutor.RunScripts | def RunScripts(self, script_dict):
"""Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files.
"""
metadata_types = ['%s-script-url', '%s-script']
metadata_keys = [key % self.script_type for key in metadata_types]
metadata_keys = [key for key in metadata_keys if script_dict.get(key)]
if not metadata_keys:
self.logger.info('No %s scripts found in metadata.', self.script_type)
for metadata_key in metadata_keys:
metadata_script = script_dict.get(metadata_key)
self._MakeExecutable(metadata_script)
self._RunScript(metadata_key, metadata_script) | python | def RunScripts(self, script_dict):
metadata_types = ['%s-script-url', '%s-script']
metadata_keys = [key % self.script_type for key in metadata_types]
metadata_keys = [key for key in metadata_keys if script_dict.get(key)]
if not metadata_keys:
self.logger.info('No %s scripts found in metadata.', self.script_type)
for metadata_key in metadata_keys:
metadata_script = script_dict.get(metadata_key)
self._MakeExecutable(metadata_script)
self._RunScript(metadata_key, metadata_script) | [
"def",
"RunScripts",
"(",
"self",
",",
"script_dict",
")",
":",
"metadata_types",
"=",
"[",
"'%s-script-url'",
",",
"'%s-script'",
"]",
"metadata_keys",
"=",
"[",
"key",
"%",
"self",
".",
"script_type",
"for",
"key",
"in",
"metadata_types",
"]",
"metadata_keys... | Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files. | [
"Run",
"the",
"metadata",
"scripts",
";",
"execute",
"a",
"URL",
"script",
"first",
"if",
"one",
"is",
"provided",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py#L67-L81 |
248,289 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/config_manager.py | ConfigManager._AddHeader | def _AddHeader(self, fp):
"""Create a file header in the config.
Args:
fp: int, a file pointer for writing the header.
"""
text = textwrap.wrap(
textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join(['# ' + line for line in text]))
fp.write('\n\n') | python | def _AddHeader(self, fp):
text = textwrap.wrap(
textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join(['# ' + line for line in text]))
fp.write('\n\n') | [
"def",
"_AddHeader",
"(",
"self",
",",
"fp",
")",
":",
"text",
"=",
"textwrap",
".",
"wrap",
"(",
"textwrap",
".",
"dedent",
"(",
"self",
".",
"config_header",
")",
",",
"break_on_hyphens",
"=",
"False",
")",
"fp",
".",
"write",
"(",
"'\\n'",
".",
"j... | Create a file header in the config.
Args:
fp: int, a file pointer for writing the header. | [
"Create",
"a",
"file",
"header",
"in",
"the",
"config",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L43-L52 |
248,290 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/config_manager.py | ConfigManager.SetOption | def SetOption(self, section, option, value, overwrite=True):
"""Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, True to overwrite an existing value in the config file.
"""
if not overwrite and self.config.has_option(section, option):
return
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, option, str(value)) | python | def SetOption(self, section, option, value, overwrite=True):
if not overwrite and self.config.has_option(section, option):
return
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, option, str(value)) | [
"def",
"SetOption",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"not",
"overwrite",
"and",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"return",
"if",
... | Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, True to overwrite an existing value in the config file. | [
"Set",
"the",
"value",
"of",
"an",
"option",
"in",
"the",
"config",
"file",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L82-L95 |
248,291 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/config_manager.py | ConfigManager.WriteConfig | def WriteConfig(self, config_file=None):
"""Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write.
"""
config_file = config_file or self.config_file
config_name = os.path.splitext(os.path.basename(config_file))[0]
config_lock = (
'%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))
with file_utils.LockFile(config_lock):
with open(config_file, 'w') as config_fp:
if self.config_header:
self._AddHeader(config_fp)
self.config.write(config_fp) | python | def WriteConfig(self, config_file=None):
config_file = config_file or self.config_file
config_name = os.path.splitext(os.path.basename(config_file))[0]
config_lock = (
'%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))
with file_utils.LockFile(config_lock):
with open(config_file, 'w') as config_fp:
if self.config_header:
self._AddHeader(config_fp)
self.config.write(config_fp) | [
"def",
"WriteConfig",
"(",
"self",
",",
"config_file",
"=",
"None",
")",
":",
"config_file",
"=",
"config_file",
"or",
"self",
".",
"config_file",
"config_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"conf... | Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write. | [
"Write",
"the",
"config",
"values",
"to",
"a",
"given",
"file",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L97-L111 |
248,292 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/logger.py | Logger | def Logger(name, debug=False, facility=None):
"""Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler's facility and priority.
Returns:
logging object, an object for logging entries.
"""
logger = logging.getLogger(name)
logger.handlers = []
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(name + ': %(levelname)s %(message)s')
if debug:
# Create a handler for console logging.
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if facility:
# Create a handler for sending logs to SysLog.
syslog_handler = logging.handlers.SysLogHandler(
address=constants.SYSLOG_SOCKET, facility=facility)
syslog_handler.setLevel(logging.INFO)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
return logger | python | def Logger(name, debug=False, facility=None):
logger = logging.getLogger(name)
logger.handlers = []
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(name + ': %(levelname)s %(message)s')
if debug:
# Create a handler for console logging.
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if facility:
# Create a handler for sending logs to SysLog.
syslog_handler = logging.handlers.SysLogHandler(
address=constants.SYSLOG_SOCKET, facility=facility)
syslog_handler.setLevel(logging.INFO)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
return logger | [
"def",
"Logger",
"(",
"name",
",",
"debug",
"=",
"False",
",",
"facility",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"handlers",
"=",
"[",
"]",
"logger",
".",
"addHandler",
"(",
"logging",
"."... | Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler's facility and priority.
Returns:
logging object, an object for logging entries. | [
"Get",
"a",
"logging",
"object",
"with",
"handlers",
"for",
"sending",
"logs",
"to",
"SysLog",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/logger.py#L22-L55 |
248,293 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._CreateSudoersGroup | def _CreateSudoersGroup(self):
"""Create a Linux group for Google added sudo user accounts."""
if not self._GetGroup(self.google_sudoers_group):
try:
command = self.groupadd_cmd.format(group=self.google_sudoers_group)
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create the sudoers group. %s.', str(e))
if not os.path.exists(self.google_sudoers_file):
try:
with open(self.google_sudoers_file, 'w') as group:
message = '%{0} ALL=(ALL:ALL) NOPASSWD:ALL'.format(
self.google_sudoers_group)
group.write(message)
except IOError as e:
self.logger.error(
'Could not write sudoers file. %s. %s',
self.google_sudoers_file, str(e))
return
file_utils.SetPermissions(
self.google_sudoers_file, mode=0o440, uid=0, gid=0) | python | def _CreateSudoersGroup(self):
if not self._GetGroup(self.google_sudoers_group):
try:
command = self.groupadd_cmd.format(group=self.google_sudoers_group)
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create the sudoers group. %s.', str(e))
if not os.path.exists(self.google_sudoers_file):
try:
with open(self.google_sudoers_file, 'w') as group:
message = '%{0} ALL=(ALL:ALL) NOPASSWD:ALL'.format(
self.google_sudoers_group)
group.write(message)
except IOError as e:
self.logger.error(
'Could not write sudoers file. %s. %s',
self.google_sudoers_file, str(e))
return
file_utils.SetPermissions(
self.google_sudoers_file, mode=0o440, uid=0, gid=0) | [
"def",
"_CreateSudoersGroup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_GetGroup",
"(",
"self",
".",
"google_sudoers_group",
")",
":",
"try",
":",
"command",
"=",
"self",
".",
"groupadd_cmd",
".",
"format",
"(",
"group",
"=",
"self",
".",
"googl... | Create a Linux group for Google added sudo user accounts. | [
"Create",
"a",
"Linux",
"group",
"for",
"Google",
"added",
"sudo",
"user",
"accounts",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L92-L114 |
248,294 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._AddUser | def _AddUser(self, user):
"""Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
"""
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create user %s. %s.', user, str(e))
return False
else:
self.logger.info('Created user account %s.', user)
return True | python | def _AddUser(self, user):
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create user %s. %s.', user, str(e))
return False
else:
self.logger.info('Created user account %s.', user)
return True | [
"def",
"_AddUser",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Creating a new user account for %s.'",
",",
"user",
")",
"command",
"=",
"self",
".",
"useradd_cmd",
".",
"format",
"(",
"user",
"=",
"user",
")",
"try",
":... | Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded. | [
"Configure",
"a",
"Linux",
"user",
"account",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L130-L149 |
248,295 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._UpdateUserGroups | def _UpdateUserGroups(self, user, groups):
"""Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded.
"""
groups = ','.join(groups)
self.logger.debug('Updating user %s with groups %s.', user, groups)
command = self.usermod_cmd.format(user=user, groups=groups)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Updated user account %s.', user)
return True | python | def _UpdateUserGroups(self, user, groups):
groups = ','.join(groups)
self.logger.debug('Updating user %s with groups %s.', user, groups)
command = self.usermod_cmd.format(user=user, groups=groups)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Updated user account %s.', user)
return True | [
"def",
"_UpdateUserGroups",
"(",
"self",
",",
"user",
",",
"groups",
")",
":",
"groups",
"=",
"','",
".",
"join",
"(",
"groups",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Updating user %s with groups %s.'",
",",
"user",
",",
"groups",
")",
"command"... | Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded. | [
"Update",
"group",
"membership",
"for",
"a",
"Linux",
"user",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L151-L171 |
248,296 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._UpdateAuthorizedKeys | def _UpdateAuthorizedKeys(self, user, ssh_keys):
"""Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exception updating a file.
OSError, raised when setting permissions or writing to a read-only
file system.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
uid = pw_entry.pw_uid
gid = pw_entry.pw_gid
home_dir = pw_entry.pw_dir
ssh_dir = os.path.join(home_dir, '.ssh')
# Not all sshd's support multiple authorized_keys files so we have to
# share one with the user. We add each of our entries as follows:
# # Added by Google
# authorized_key_entry
authorized_keys_file = os.path.join(ssh_dir, 'authorized_keys')
# Do not write to the authorized keys file if it is a symlink.
if os.path.islink(ssh_dir) or os.path.islink(authorized_keys_file):
self.logger.warning(
'Not updating authorized keys for user %s. File is a symlink.', user)
return
# Create home directory if it does not exist. This can happen if _GetUser
# (getpwnam) returns non-local user info (e.g., from LDAP).
if not os.path.exists(home_dir):
file_utils.SetPermissions(home_dir, mode=0o755, uid=uid, gid=gid,
mkdir=True)
# Create ssh directory if it does not exist.
file_utils.SetPermissions(ssh_dir, mode=0o700, uid=uid, gid=gid, mkdir=True)
# Create entry in the authorized keys file.
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_keys:
updated_keys_file = updated_keys.name
if os.path.exists(authorized_keys_file):
lines = open(authorized_keys_file).readlines()
else:
lines = []
google_lines = set()
for i, line in enumerate(lines):
if line.startswith(self.google_comment):
google_lines.update([i, i+1])
# Write user's authorized key entries.
for i, line in enumerate(lines):
if i not in google_lines and line:
line += '\n' if not line.endswith('\n') else ''
updated_keys.write(line)
# Write the Google authorized key entries at the end of the file.
# Each entry is preceded by '# Added by Google'.
for ssh_key in ssh_keys:
ssh_key += '\n' if not ssh_key.endswith('\n') else ''
updated_keys.write('%s\n' % self.google_comment)
updated_keys.write(ssh_key)
# Write buffered data to the updated keys file without closing it and
# update the Linux user's authorized keys file.
updated_keys.flush()
shutil.copy(updated_keys_file, authorized_keys_file)
file_utils.SetPermissions(
authorized_keys_file, mode=0o600, uid=uid, gid=gid) | python | def _UpdateAuthorizedKeys(self, user, ssh_keys):
pw_entry = self._GetUser(user)
if not pw_entry:
return
uid = pw_entry.pw_uid
gid = pw_entry.pw_gid
home_dir = pw_entry.pw_dir
ssh_dir = os.path.join(home_dir, '.ssh')
# Not all sshd's support multiple authorized_keys files so we have to
# share one with the user. We add each of our entries as follows:
# # Added by Google
# authorized_key_entry
authorized_keys_file = os.path.join(ssh_dir, 'authorized_keys')
# Do not write to the authorized keys file if it is a symlink.
if os.path.islink(ssh_dir) or os.path.islink(authorized_keys_file):
self.logger.warning(
'Not updating authorized keys for user %s. File is a symlink.', user)
return
# Create home directory if it does not exist. This can happen if _GetUser
# (getpwnam) returns non-local user info (e.g., from LDAP).
if not os.path.exists(home_dir):
file_utils.SetPermissions(home_dir, mode=0o755, uid=uid, gid=gid,
mkdir=True)
# Create ssh directory if it does not exist.
file_utils.SetPermissions(ssh_dir, mode=0o700, uid=uid, gid=gid, mkdir=True)
# Create entry in the authorized keys file.
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_keys:
updated_keys_file = updated_keys.name
if os.path.exists(authorized_keys_file):
lines = open(authorized_keys_file).readlines()
else:
lines = []
google_lines = set()
for i, line in enumerate(lines):
if line.startswith(self.google_comment):
google_lines.update([i, i+1])
# Write user's authorized key entries.
for i, line in enumerate(lines):
if i not in google_lines and line:
line += '\n' if not line.endswith('\n') else ''
updated_keys.write(line)
# Write the Google authorized key entries at the end of the file.
# Each entry is preceded by '# Added by Google'.
for ssh_key in ssh_keys:
ssh_key += '\n' if not ssh_key.endswith('\n') else ''
updated_keys.write('%s\n' % self.google_comment)
updated_keys.write(ssh_key)
# Write buffered data to the updated keys file without closing it and
# update the Linux user's authorized keys file.
updated_keys.flush()
shutil.copy(updated_keys_file, authorized_keys_file)
file_utils.SetPermissions(
authorized_keys_file, mode=0o600, uid=uid, gid=gid) | [
"def",
"_UpdateAuthorizedKeys",
"(",
"self",
",",
"user",
",",
"ssh_keys",
")",
":",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"not",
"pw_entry",
":",
"return",
"uid",
"=",
"pw_entry",
".",
"pw_uid",
"gid",
"=",
"pw_entry",
".",
... | Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exception updating a file.
OSError, raised when setting permissions or writing to a read-only
file system. | [
"Update",
"the",
"authorized",
"keys",
"file",
"for",
"a",
"Linux",
"user",
"with",
"a",
"list",
"of",
"SSH",
"keys",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L173-L249 |
248,297 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._UpdateSudoer | def _UpdateSudoer(self, user, sudoer=False):
"""Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded.
"""
if sudoer:
self.logger.info('Adding user %s to the Google sudoers group.', user)
command = self.gpasswd_add_cmd.format(
user=user, group=self.google_sudoers_group)
else:
self.logger.info('Removing user %s from the Google sudoers group.', user)
command = self.gpasswd_remove_cmd.format(
user=user, group=self.google_sudoers_group)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Removed user %s from the Google sudoers group.', user)
return True | python | def _UpdateSudoer(self, user, sudoer=False):
if sudoer:
self.logger.info('Adding user %s to the Google sudoers group.', user)
command = self.gpasswd_add_cmd.format(
user=user, group=self.google_sudoers_group)
else:
self.logger.info('Removing user %s from the Google sudoers group.', user)
command = self.gpasswd_remove_cmd.format(
user=user, group=self.google_sudoers_group)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Removed user %s from the Google sudoers group.', user)
return True | [
"def",
"_UpdateSudoer",
"(",
"self",
",",
"user",
",",
"sudoer",
"=",
"False",
")",
":",
"if",
"sudoer",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Adding user %s to the Google sudoers group.'",
",",
"user",
")",
"command",
"=",
"self",
".",
"gpasswd_ad... | Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded. | [
"Update",
"sudoer",
"group",
"membership",
"for",
"a",
"Linux",
"user",
"account",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L251-L277 |
248,298 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils._RemoveAuthorizedKeys | def _RemoveAuthorizedKeys(self, user):
"""Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if os.path.exists(authorized_keys_file):
try:
os.remove(authorized_keys_file)
except OSError as e:
message = 'Could not remove authorized keys for user %s. %s.'
self.logger.warning(message, user, str(e)) | python | def _RemoveAuthorizedKeys(self, user):
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if os.path.exists(authorized_keys_file):
try:
os.remove(authorized_keys_file)
except OSError as e:
message = 'Could not remove authorized keys for user %s. %s.'
self.logger.warning(message, user, str(e)) | [
"def",
"_RemoveAuthorizedKeys",
"(",
"self",
",",
"user",
")",
":",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"not",
"pw_entry",
":",
"return",
"home_dir",
"=",
"pw_entry",
".",
"pw_dir",
"authorized_keys_file",
"=",
"os",
".",
"pat... | Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access. | [
"Remove",
"a",
"Linux",
"user",
"account",
"s",
"authorized",
"keys",
"file",
"to",
"prevent",
"login",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L279-L296 |
248,299 | GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py | AccountsUtils.GetConfiguredUsers | def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [user.strip() for user in users] | python | def GetConfiguredUsers(self):
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [user.strip() for user in users] | [
"def",
"GetConfiguredUsers",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"google_users_file",
")",
":",
"users",
"=",
"open",
"(",
"self",
".",
"google_users_file",
")",
".",
"readlines",
"(",
")",
"else",
":",
"use... | Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google. | [
"Retrieve",
"the",
"list",
"of",
"configured",
"Google",
"user",
"accounts",
"."
] | 53ea8cd069fb4d9a1984d1c167e54c133033f8da | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L298-L308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.