uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
bf36b4e570ff1f3e407ff6dd
train
function
def graph_day_of_month(df): '''Creates graph for results based on day of the month''' mndf, ctdf = mn_ct_df(df, 'day') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'day') mndf.plot.scatter(x='day', y='result', legend=False) plt.title('Result by Day of the Month') plt.xlabel('Day of the...
def graph_day_of_month(df):
'''Creates graph for results based on day of the month''' mndf, ctdf = mn_ct_df(df, 'day') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'day') mndf.plot.scatter(x='day', y='result', legend=False) plt.title('Result by Day of the Month') plt.xlabel('Day of the Month') plt.xlim(0, 32)...
lim(-.25, 24) plt.xticks(ticks=np.arange(0, 25, step=4)) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc * 2)) plt.yticks(ticks=np.arange(mnc, (mxc - inc * 2) + 1, step=inc)) plt.show() def graph_day_of_month(df):
88
88
295
7
81
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
graph_day_of_month
graph_day_of_month
220
243
220
220
d8442c7b7b4cf0c39cf584a9c4a3bc3e204605c8
bigcode/the-stack
train
c66ff4d8f6797d9133896a4d
train
function
def result_by_elo_diff(df): '''Creates graph for results based on difference in ELO''' mndf, ctdf = mn_ct_df(df, 'bin_diff') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_diff') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_diff') mndf.plot.scatter(x='bin_diff', y='result', legend=False...
def result_by_elo_diff(df):
'''Creates graph for results based on difference in ELO''' mndf, ctdf = mn_ct_df(df, 'bin_diff') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_diff') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_diff') mndf.plot.scatter(x='bin_diff', y='result', legend=False) plt.title('Result by D...
Opposition ELO') plt.xlim(xmn, xmx) plt.xticks(ticks=np.arange(xmn, xmx + xin, step=xin)) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc * 2)) plt.yticks(ticks=np.arange(mnc, (mxc - inc * 2) + 1, step=inc)) plt.show() def result_by_elo_diff(df):
98
98
327
8
90
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
result_by_elo_diff
result_by_elo_diff
423
447
423
423
5abf427fdfd855db9283388552f9c8446849dfa6
bigcode/the-stack
train
afbc0dfcf1213b69f49f698a
train
function
def get_graph_df(file_name): '''Input: file_name = csv file to clean for graphing Creates the dataframe from the file Converts the time used from seconds to percentage of the time allowed Bins: - difference in elo - elo - opp's elo - Number of moves - Time used - Time used b...
def get_graph_df(file_name):
'''Input: file_name = csv file to clean for graphing Creates the dataframe from the file Converts the time used from seconds to percentage of the time allowed Bins: - difference in elo - elo - opp's elo - Number of moves - Time used - Time used by opp returns: df = ...
# Author: Mohit Gangwani # Date: 11/15/2018 # Git-Hub: Data-is-Life import matplotlib.pyplot as plt import pandas as pd import numpy as np plt.style.use('seaborn-whitegrid') def custom_round_int(x, base=20): '''Helps to round integers''' return int(base * round(float(x) / base)) def custom_round_flt(x, ba...
126
209
698
7
119
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
get_graph_df
get_graph_df
23
94
23
23
4fed0d27dcb569ba83280ed890cae5ffb78ff97f
bigcode/the-stack
train
d6e0ecf548b6d01ed017f36d
train
function
def game_time(df): '''Creates graph for results based on the game time allowed per player''' mndf, ctdf = mn_ct_df(df, 'game_time') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'game_time') mndf.plot.scatter(x='game_time', y='result', legend=False) plt.title('Result by Game Time') plt....
def game_time(df):
'''Creates graph for results based on the game time allowed per player''' mndf, ctdf = mn_ct_df(df, 'game_time') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'game_time') mndf.plot.scatter(x='game_time', y='result', legend=False) plt.title('Result by Game Time') plt.xlabel('Game Time (...
.02) plt.xticks(ticks=[-1, 0, 1], labels=['DNC', 'Queen-side', 'King-side']) plt.ylabel('# of Games') plt.ylim((mnc + inc), (mxc - inc * 2)) plt.yticks(ticks=np.arange((mnc + inc), (mxc - inc), step=inc)) plt.show() def game_time(df):
91
91
304
5
86
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
game_time
game_time
326
349
326
326
c9fb35efa2496e9efdf3d6e54bc8f42638dfe97f
bigcode/the-stack
train
6288ac86f5269ad1cb22c26f
train
function
def mn_ct_df(df, col_name): '''Input: - df = dataframe for analysis loaded from the csv file - col_name = column name to evaluate Creates two dataframes from the main df and returns: - mndf = mean of all the values based on the selected column - ctdf = sum of all the values based on the selecte...
def mn_ct_df(df, col_name):
'''Input: - df = dataframe for analysis loaded from the csv file - col_name = column name to evaluate Creates two dataframes from the main df and returns: - mndf = mean of all the values based on the selected column - ctdf = sum of all the values based on the selected column''' mndf = df.g...
_time_used, bins=bn_ot, labels=bn_ot[:-1]).astype(float) df.drop(columns=['elo', 'opp_elo', 'diff', 'num_moves', 'time_used', 'opp_time_used'], inplace=True) return df def mn_ct_df(df, col_name):
64
64
134
9
54
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
mn_ct_df
mn_ct_df
97
111
97
97
3c66f86d37d3f3597aca03e34acef79462b2c7f9
bigcode/the-stack
train
b4176010d860c75ba3b82811
train
function
def opp_castled_or_not(df): '''Creates graph for results based if and where the opposition castled the king''' mndf, ctdf = mn_ct_df(df, 'opp_castled') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'opp_castled') mndf.plot.scatter(x='opp_castled', y='result', legend=False) plt.title(...
def opp_castled_or_not(df):
'''Creates graph for results based if and where the opposition castled the king''' mndf, ctdf = mn_ct_df(df, 'opp_castled') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'opp_castled') mndf.plot.scatter(x='opp_castled', y='result', legend=False) plt.title('Result by Opposition Castli...
(-1.02, 1.02) plt.xticks(ticks=[-1, 0, 1], labels=['DNC', 'Queen-side', 'King-side']) plt.ylabel('# of Games') plt.ylim((mnc + inc), (mxc - inc * 2)) plt.yticks(ticks=np.arange((mnc + inc), (mxc - inc), step=inc)) plt.show() def opp_castled_or_not(df):
101
101
337
8
93
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
opp_castled_or_not
opp_castled_or_not
299
323
299
299
4dfbbe092c1f67946aaf1646f93598f20b6bdf4a
bigcode/the-stack
train
0d0cc4b40e01724b71bebf4d
train
function
def opp_move_num_castled(df): '''Creates graph for results based on move number the opposition castled''' mndf, ctdf = mn_ct_df(df, 'opp_castled_on') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'opp_castled_on') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'opp_castled_on') mndf.plot.scatter(x...
def opp_move_num_castled(df):
'''Creates graph for results based on move number the opposition castled''' mndf, ctdf = mn_ct_df(df, 'opp_castled_on') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'opp_castled_on') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'opp_castled_on') mndf.plot.scatter(x='opp_castled_on', y='result',...
Move # of Castling') plt.xlim(xmn, xmx + xin) plt.xticks(ticks=np.arange(xmn, xmx + xin + 1, step=xin)) plt.ylabel('# of Games') inc = custom_round_int((smyx - mnc) / 10) plt.ylim(mnc, smyx + inc) plt.yticks(ticks=np.arange(mnc, (smyx + inc * 2), step=inc)) plt.show() def opp_move_num_castle...
115
115
385
8
107
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
opp_move_num_castled
opp_move_num_castled
533
558
533
533
1968158e9889e704b8b9f0fd25b4fba7f68949e4
bigcode/the-stack
train
29f6484f9a35bf82958c2ef6
train
function
def result_by_opp_time_used(df): '''Creates graph for results based on percentage of allowed time used by the opposition''' mndf, ctdf = mn_ct_df(df, 'bin_opp_time_used') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_opp_time_used') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_opp_ti...
def result_by_opp_time_used(df):
'''Creates graph for results based on percentage of allowed time used by the opposition''' mndf, ctdf = mn_ct_df(df, 'bin_opp_time_used') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_opp_time_used') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_opp_time_used') mndf.plot.scatter(...
('Amount of Time Used(%)') plt.xlim(xmn, xmx + 5) plt.xticks(ticks=np.arange(xmn, xmx + 6, step=xin)) plt.ylabel('# of Games') inc = custom_round_int(((smyx - mnc) / 5), 10) plt.ylim(mnc, smyx) plt.yticks(ticks=np.arange(mnc, (smyx + inc), step=inc)) plt.show() def result_by_opp_time_used(df...
115
115
384
9
106
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
result_by_opp_time_used
result_by_opp_time_used
590
616
590
590
f643e6bb2094467f4592e41bb2e7e0432e7c7dc5
bigcode/the-stack
train
8661f07e7328867273e6cd21
train
function
def move_num_castled(df): '''Creates graph for results based on move number if the player castled''' mndf, ctdf = mn_ct_df(df, 'castled_on') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'castled_on') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'castled_on') mndf.plot.scatter(x='castled_on', y=...
def move_num_castled(df):
'''Creates graph for results based on move number if the player castled''' mndf, ctdf = mn_ct_df(df, 'castled_on') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'castled_on') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'castled_on') mndf.plot.scatter(x='castled_on', y='result', legend=False) ...
plt.title('# of Games by Number of Moves') plt.xlabel('Number of Moves') plt.xlim(xmn, xmx + 5) plt.xticks(ticks=np.arange(xmn, xmx + xin + 5, step=xin)) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc)) plt.yticks(ticks=np.arange(mnc, (mxc - inc) + 1, step=inc)) plt.show() def move_nu...
111
111
373
7
104
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
move_num_castled
move_num_castled
505
530
505
505
4348eeeed39b243a5189bd2154ad5fbcdc7048d5
bigcode/the-stack
train
9fa6e4deccb4caf591882530
train
function
def opp_result_elo(df): '''Creates graph for results based on starting opposition ELO''' mndf, ctdf = mn_ct_df(df, 'bin_opp_elo') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_opp_elo') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_opp_elo') mndf.plot.scatter(x='bin_opp_elo', y='result'...
def opp_result_elo(df):
'''Creates graph for results based on starting opposition ELO''' mndf, ctdf = mn_ct_df(df, 'bin_opp_elo') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_opp_elo') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_opp_elo') mndf.plot.scatter(x='bin_opp_elo', y='result', legend=False) plt....
.title('# of Games by ELO') plt.xlabel('ELO') plt.xlim(xmn, xmx) plt.xticks(ticks=np.arange(xmn, xmx + xin, step=xin)) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc)) plt.yticks(ticks=np.arange(mnc, (mxc - inc) + 1, step=inc)) plt.show() def opp_result_elo(df):
101
101
339
7
94
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
opp_result_elo
opp_result_elo
396
420
396
396
b0d36a77c51e8a3f346292857072a6740b8b6637
bigcode/the-stack
train
7de95664f014f52f7cfb882b
train
function
def result_elo(df): '''Creates graph for results based on starting ELO''' mndf, ctdf = mn_ct_df(df, 'bin_elo') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_elo') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_elo') mndf.plot.scatter(x='bin_elo', y='result', legend=False) plt.title('...
def result_elo(df):
'''Creates graph for results based on starting ELO''' mndf, ctdf = mn_ct_df(df, 'bin_elo') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_elo') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_elo') mndf.plot.scatter(x='bin_elo', y='result', legend=False) plt.title('Result by ELO') ...
('Result by Color') plt.xlabel('Color') plt.xlim(-.03, 1.01) plt.xticks(ticks=[0, 1], labels=['Black', 'White']) plt.ylabel('Winning Ratio') plt.ylim(mnm, mxm) plt.yticks(ticks=np.arange(mnm, mxm + rnm / 2, step=rnm)) plt.show() def result_elo(df):
94
94
315
6
88
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
result_elo
result_elo
369
393
369
369
7a111d9e776af42b373d32b4c5acfd79ed3fcd6b
bigcode/the-stack
train
ff4f32deba1b986a79f35208
train
function
def day_of_week(df): '''Creates graph for results based on day of week''' mndf, ctdf = mn_ct_df(df, 'weekday') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'weekday') mndf.plot.scatter(x='weekday', y='result', legend=False) plt.title('Result by Day of the Week') plt.xlabel('Weekday') ...
def day_of_week(df):
'''Creates graph for results based on day of week''' mndf, ctdf = mn_ct_df(df, 'weekday') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'weekday') mndf.plot.scatter(x='weekday', y='result', legend=False) plt.title('Result by Day of the Week') plt.xlabel('Weekday') plt.xticks(ticks=n...
') plt.xlim(0, 32) plt.xticks(ticks=np.arange(0, 32, step=5)) plt.ylabel('# of Games') plt.ylim((mnc + inc), (mxc - inc)) plt.yticks(ticks=np.arange((mnc + inc), (mxc - inc) + 1, step=inc)) plt.show() def day_of_week(df):
90
90
301
6
84
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
day_of_week
day_of_week
246
269
246
246
2f37facb5b1f289f2e3d1fee48a6e52673497b77
bigcode/the-stack
train
39cd6f1644fee13ed8483f6e
train
function
def graph_lim(mndf, ctdf, col_name): '''Input: - mndf = dataframe created for mean values of specified column - ctdf = dataframe created for sum values of specified column - col_name = column name to evaluate Creates graph limits of the y-axis and returns: - mnm = minimum y-axis value for mean ...
def graph_lim(mndf, ctdf, col_name):
'''Input: - mndf = dataframe created for mean values of specified column - ctdf = dataframe created for sum values of specified column - col_name = column name to evaluate Creates graph limits of the y-axis and returns: - mnm = minimum y-axis value for mean value graph - mxm = maximum y-axi...
return df def mn_ct_df(df, col_name): '''Input: - df = dataframe for analysis loaded from the csv file - col_name = column name to evaluate Creates two dataframes from the main df and returns: - mndf = mean of all the values based on the selected column - ctdf = sum of all the values based o...
151
151
505
14
136
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
graph_lim
graph_lim
114
161
114
114
681a432bd7af52d4d2fecf5d9b3a8c3a757fd4c5
bigcode/the-stack
train
9e4306720fd0eb15900ef2db
train
function
def custom_round_flt(x, base=.01): '''Helps to round floats under 1.00''' return base * round(float(x) / base)
def custom_round_flt(x, base=.01):
'''Helps to round floats under 1.00''' return base * round(float(x) / base)
as plt import pandas as pd import numpy as np plt.style.use('seaborn-whitegrid') def custom_round_int(x, base=20): '''Helps to round integers''' return int(base * round(float(x) / base)) def custom_round_flt(x, base=.01):
64
64
35
11
53
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
custom_round_flt
custom_round_flt
17
20
17
17
a7116dc35e325f3ba71a405f65cbbea1bcc5588e
bigcode/the-stack
train
27457736f76288d8a044fece
train
function
def number_of_moves(df): '''Creates graph for results based on number of moves per player''' mndf, ctdf = mn_ct_df(df, 'bin_num_moves') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_num_moves') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_num_moves') mndf.plot.scatter(x='bin_num_moves'...
def number_of_moves(df):
'''Creates graph for results based on number of moves per player''' mndf, ctdf = mn_ct_df(df, 'bin_num_moves') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_num_moves') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_num_moves') mndf.plot.scatter(x='bin_num_moves', y='result', legend=Fals...
.arange(9), labels=['Rule', 'Stlmte', 'Rptn', 'Agr', 'Matrl', 'Abndn', 'Time', 'Rsgn', 'Chmte']) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc)) plt.yticks(ticks=np.arange(mnc, (mxc - inc) + 1, step=inc)) plt.show(...
99
99
333
6
93
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
number_of_moves
number_of_moves
478
502
478
478
45b7f64b08ae4b099da883e4eecf50247243dd42
bigcode/the-stack
train
38ec8c09c75c6dbfd29d0b15
train
function
def custom_round_int(x, base=20): '''Helps to round integers''' return int(base * round(float(x) / base))
def custom_round_int(x, base=20):
'''Helps to round integers''' return int(base * round(float(x) / base))
# Author: Mohit Gangwani # Date: 11/15/2018 # Git-Hub: Data-is-Life import matplotlib.pyplot as plt import pandas as pd import numpy as np plt.style.use('seaborn-whitegrid') def custom_round_int(x, base=20):
64
64
30
10
54
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
custom_round_int
custom_round_int
11
14
11
11
e536f998876a039dc3cbbe2d7a06f77eae4798ed
bigcode/the-stack
train
4b0d68aba24337cea9f87a61
train
function
def result_by_time_used(df): '''Creates graph for results based on percentage of allowed time used by the player''' mndf, ctdf = mn_ct_df(df, 'bin_time_used') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_time_used') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_time_used') mndf....
def result_by_time_used(df):
'''Creates graph for results based on percentage of allowed time used by the player''' mndf, ctdf = mn_ct_df(df, 'bin_time_used') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'bin_time_used') xmn, xmx, xin, smyx = x_axis_lims(ctdf, 'bin_time_used') mndf.plot.scatter(x='bin_time_used...
(xmn, xmx + (xin * 2)) plt.xticks(ticks=np.arange(xmn, (xmx + (xin * 2)) + 1, step=xin)) plt.ylabel('# of Games') inc = custom_round_int((smyx - mnc) / 10) plt.ylim(mnc, smyx) plt.yticks(ticks=np.arange(mnc, (smyx + inc), step=inc)) plt.show() def result_by_time_used(df):
109
109
366
7
102
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
result_by_time_used
result_by_time_used
561
587
561
561
3592ec7095c63db3cc900d86c99d6f16346ff2bd
bigcode/the-stack
train
c347a9f1d04895d6cc9bea12
train
function
def won_via(df): '''Creates graph for results based on how the game ended''' mndf, ctdf = mn_ct_df(df, 'won_by') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'won_by') mndf.plot.scatter(x='won_by', y='result', legend=False) plt.title('Result by the Result Type') plt.xlabel('Result Type...
def won_via(df):
'''Creates graph for results based on how the game ended''' mndf, ctdf = mn_ct_df(df, 'won_by') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'won_by') mndf.plot.scatter(x='won_by', y='result', legend=False) plt.title('Result by the Result Type') plt.xlabel('Result Type') plt.xticks...
plt.xlabel('Difference in ELO') plt.xlim(xmn, xmx) plt.xticks(ticks=np.arange(xmn, xmx + xin, step=xin)) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc * 2)) plt.yticks(ticks=np.arange(mnc, (mxc - inc * 2) + 1, step=inc)) plt.show() def won_via(df):
99
99
332
6
93
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
won_via
won_via
450
475
450
450
de1d3cc2c2517e08c509114e909064cb1f44f4f9
bigcode/the-stack
train
790441714e88c151d5011879
train
function
def graph_start_time(df): '''Creates graph for results based on starting time of the game''' mndf, ctdf = mn_ct_df(df, 'start_time') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'start_time') mndf.plot.scatter(x='start_time', y='result', legend=False) plt.title('Result by Time of Day') ...
def graph_start_time(df):
'''Creates graph for results based on starting time of the game''' mndf, ctdf = mn_ct_df(df, 'start_time') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'start_time') mndf.plot.scatter(x='start_time', y='result', legend=False) plt.title('Result by Time of Day') plt.xlabel('Starting Time...
int(xmx / xin) xmn = custom_round_int((xmn - int(xmn / xin)), 10) xmx = custom_round_int((xmx - int(xmx / xin)), 10) tlgst = ctdf['result'].nlargest(2) smyx = tlgst.min() return xmn, xmx, xin, smyx def graph_start_time(df):
88
88
295
6
81
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
graph_start_time
graph_start_time
194
217
194
194
358a08f3ac92c9ee92fff3f0f7a653ff1c866db9
bigcode/the-stack
train
cda31aaef4e713d82fa669de
train
function
def x_axis_lims(ctdf, col_name): '''Input: ctdf = dataframe created for sum values of specified column col_name = column name to evaluate Creates graph limits of the x-axis and returns: - xmn = minimum x-axis value for both graphs - xmx = maximum x-axis value for both graphs - xin = interva...
def x_axis_lims(ctdf, col_name):
'''Input: ctdf = dataframe created for sum values of specified column col_name = column name to evaluate Creates graph limits of the x-axis and returns: - xmn = minimum x-axis value for both graphs - xmx = maximum x-axis value for both graphs - xin = interval x-axis value for both graphs ...
10), 10) mnm -= rnm mxm += rnm mnc -= inc * 2 mxc += inc * 2 if mnc < -2: mnc = 0 return mnm, mxm, rnm, mnc, mxc, inc def x_axis_lims(ctdf, col_name):
83
83
279
11
71
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
x_axis_lims
x_axis_lims
164
191
164
164
edce098caae356f051f7a2995a09a44b0c98170a
bigcode/the-stack
train
ae65141767cc0edb85072870
train
function
def result_by_color(df): '''Creates graph for results based color assigned''' mndf, ctdf = mn_ct_df(df, 'color') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'color') mndf.plot.scatter(x='color', y='result', legend=False) plt.title('Result by Color') plt.xlabel('Color') plt.xlim(-....
def result_by_color(df):
'''Creates graph for results based color assigned''' mndf, ctdf = mn_ct_df(df, 'color') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'color') mndf.plot.scatter(x='color', y='result', legend=False) plt.title('Result by Color') plt.xlabel('Color') plt.xlim(-.03, 1.01) plt.xticks(...
=[180, 300, 600]) plt.ylabel('# of Games') plt.ylim(mnc, (mxc - inc)) plt.yticks(ticks=np.arange(mnc, (mxc - inc) + 1, step=inc)) plt.show() def result_by_color(df):
64
64
172
6
58
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
result_by_color
result_by_color
352
366
352
352
4e98ccdee05b58837f13e0557b1834388097bdac
bigcode/the-stack
train
aa8c5caf8ab0bace362d7701
train
function
def castled_or_not(df): '''Creates graph for results based if and where the king was castled''' mndf, ctdf = mn_ct_df(df, 'castled') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'castled') mndf.plot.scatter(x='castled', y='result', legend=False) plt.title('Result by Castling') plt.xlab...
def castled_or_not(df):
'''Creates graph for results based if and where the king was castled''' mndf, ctdf = mn_ct_df(df, 'castled') mnm, mxm, rnm, mnc, mxc, inc = graph_lim(mndf, ctdf, 'castled') mndf.plot.scatter(x='castled', y='result', legend=False) plt.title('Result by Castling') plt.xlabel('Castled') plt.xl...
plt.xticks(ticks=np.arange(7), labels=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) plt.ylabel('# of Games') plt.ylim((mnc + inc), (mxc - inc)) plt.yticks(ticks=np.arange((mnc + inc), (mxc - inc) + 1, step=inc)) plt.show() def castled_or_not(df):
96
96
323
7
89
Data-is-life/lots-of-data
src/old_files/all_graphs.py
Python
castled_or_not
castled_or_not
272
296
272
272
b2cc7a644ad2f7328ef382d0494fc14f2de56840
bigcode/the-stack
train
b96d2e32ee545e874b933484
train
class
class AcrCommandsTests(ScenarioTest): def _core_registry_scenario(self, registry_name, resource_group, location): self.cmd('acr check-name -n {}'.format(registry_name), checks=[self.check('nameAvailable', False), self.check('reason', 'AlreadyExists')]) self...
class AcrCommandsTests(ScenarioTest):
def _core_registry_scenario(self, registry_name, resource_group, location): self.cmd('acr check-name -n {}'.format(registry_name), checks=[self.check('nameAvailable', False), self.check('reason', 'AlreadyExists')]) self.cmd('acr list -g {}'.format(resource_g...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
95
256
7,698
8
86
chunyu3/azure-cli
src/azure-cli/azure/cli/command_modules/acr/tests/latest/test_acr_commands.py
Python
AcrCommandsTests
AcrCommandsTests
11
618
11
12
40677481a256320d5bb1d634876471d487dea969
bigcode/the-stack
train
14777595872d3574b1c4dcdb
train
class
class XValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__(self, plotly_name="x", parent_name="funnelarea.domain", **kwargs): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc")...
class XValidator(_plotly_utils.basevalidators.InfoArrayValidator):
def __init__(self, plotly_name="x", parent_name="funnelarea.domain", **kwargs): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), items=kwargs.pop( "items", ...
import _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.InfoArrayValidator):
21
64
151
13
7
mastermind88/plotly.py
packages/python/plotly/plotly/validators/funnelarea/domain/_x.py
Python
XValidator
XValidator
4
18
4
4
f8d510dd04147786a92c45b4b8f7f4caf436aa71
bigcode/the-stack
train
8aa05969ebfaa1db9f0dd681
train
class
class ColorBar(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "parcats.line" _path_str = "parcats.line.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "len", ...
class ColorBar(_BaseTraceHierarchyType): # class properties # --------------------
_parent_path_str = "parcats.line" _path_str = "parcats.line.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "len", "lenmode", "nticks", "outlinecolor", "outlinewidth", "sepa...
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class ColorBar(_BaseTraceHierarchyType): # class properties # --------------------
43
256
16,687
18
24
benlindsay/plotly.py
packages/python/plotly/plotly/graph_objs/parcats/line/_colorbar.py
Python
ColorBar
ColorBar
5
1,939
5
8
b80768439b7c960e2c82f093a9da93733a09954f
bigcode/the-stack
train
779256f6a1f3814aa60708ed
train
class
class HelloSerializers(serializers.Serializer): """serializers for test api view""" name=serializers.CharField(max_length=10)
class HelloSerializers(serializers.Serializer):
"""serializers for test api view""" name=serializers.CharField(max_length=10)
from rest_framework import serializers from profiles_api import models class HelloSerializers(serializers.Serializer):
19
64
28
7
11
prakash789/profiles-rest-api
profiles_api/serializers.py
Python
HelloSerializers
HelloSerializers
4
6
4
4
0146487fa576504d8b6a3af0a16349289ea5934e
bigcode/the-stack
train
ab2314e72a9fec45de81b0b3
train
class
class ProfileFeedItemSerializer(serializers.ModelSerializer): """Serializes profile feed items""" class Meta: model = models.ProfileFeedItem fields = ('id', 'user_profile', 'status_text', 'created_on') extra_kwargs = {'user_profile': {'read_only': True}}
class ProfileFeedItemSerializer(serializers.ModelSerializer):
"""Serializes profile feed items""" class Meta: model = models.ProfileFeedItem fields = ('id', 'user_profile', 'status_text', 'created_on') extra_kwargs = {'user_profile': {'read_only': True}}
{'input_type':'password'}}} def create(self, validated_data): user = models.UserProfile.objects.create_user(email=validated_data['email'], name=validated_data['name'], password=validated_data['passw...
64
64
61
9
54
prakash789/profiles-rest-api
profiles_api/serializers.py
Python
ProfileFeedItemSerializer
ProfileFeedItemSerializer
25
31
25
25
acb6f7254c0fb36a22b22264de60e0fd5fd35d55
bigcode/the-stack
train
9050180d9d2102a687114152
train
class
class UserProfileSerializer(serializers.ModelSerializer): """sericalser a user profile objects""" class Meta: model= models.UserProfile fields=('id','email','name','password') extra_kwargs={'password':{'write_only':True,'style':{'input_type':'password'}}} def create(self, validated_...
class UserProfileSerializer(serializers.ModelSerializer):
"""sericalser a user profile objects""" class Meta: model= models.UserProfile fields=('id','email','name','password') extra_kwargs={'password':{'write_only':True,'style':{'input_type':'password'}}} def create(self, validated_data): user = models.UserProfile.objects.create_u...
from rest_framework import serializers from profiles_api import models class HelloSerializers(serializers.Serializer): """serializers for test api view""" name=serializers.CharField(max_length=10) #age=serializers.IntegerField(max_value=None, min_value=None) class UserProfileSerializer(serializers.ModelSer...
64
64
109
8
56
prakash789/profiles-rest-api
profiles_api/serializers.py
Python
UserProfileSerializer
UserProfileSerializer
9
23
9
9
c86e9cb5b6efa6e657b38b7388873ad3a9580c15
bigcode/the-stack
train
c08edd42ae21ec0556cbc181
train
class
class Graph: def __init__(self, board_shim): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.board_id = board_shim.get_board_id() self.board_shim = board_shim self.exg_channels = BoardShim.get_exg_channels(self.board_id) self.sampling...
class Graph:
def __init__(self, board_shim): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.board_id = board_shim.get_board_id() self.board_shim = board_shim self.exg_channels = BoardShim.get_exg_channels(self.board_id) self.sampling_rate = Board...
import argparse import logging import pyqtgraph as pg from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, WindowFunctions, DetrendOperations from pyqtgraph.Qt import QtGui, QtCore class Graph:
66
256
1,390
3
62
Andrey1994/brainflow
python_package/examples/plot_real_time/plot_real_time.py
Python
Graph
Graph
10
117
10
10
3b5e28966babc34569b3a0a7969e030ecd39412f
bigcode/the-stack
train
e90269e8a6cd2ccf032b0930
train
function
def main(): BoardShim.enable_dev_board_logger() logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--timeout', type=int, help='timeout for device disc...
def main():
BoardShim.enable_dev_board_logger() logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--timeout', type=int, help='timeout for device discovery or con...
) avg_bands[2] = avg_bands[2] + DataFilter.get_band_power(psd_data, 8.0, 13.0) avg_bands[3] = avg_bands[3] + DataFilter.get_band_power(psd_data, 13.0, 30.0) avg_bands[4] = avg_bands[4] + DataFilter.get_band_power(psd_data, 30.0, 50.0) avg_bands = [int(x * 100 / l...
149
149
499
3
146
Andrey1994/brainflow
python_package/examples/plot_real_time/plot_real_time.py
Python
main
main
120
163
120
120
cd19d70f96c51252152041cf4684e4d0d7a73cbd
bigcode/the-stack
train
beb40c4897ddb84fcc721578
train
class
class InvalidTranslationUnitException(TypeError): """When a translation unit is invalid""" pass
class InvalidTranslationUnitException(TypeError):
"""When a translation unit is invalid""" pass
when its not actually part of that initiwlization value.""" pass class InvalidDefinitionError(TypeError): """When a structure is invalid in the source code, sizeof, alignof returns negatives value. We detect it and do our best.""" pass class InvalidTranslationUnitException(TypeError):
64
64
20
8
55
rviollette/ctypeslib
ctypeslib/codegen/handler.py
Python
InvalidTranslationUnitException
InvalidTranslationUnitException
26
29
26
27
b4edd0f8f42f02bfee84e000ea1a247eb3e7d24e
bigcode/the-stack
train
b04960cad80523376d99ecbb
train
class
class CursorKindException(TypeError): """When a child node of a VAR_DECL is parsed as an initialization value, when its not actually part of that initiwlization value.""" pass
class CursorKindException(TypeError):
"""When a child node of a VAR_DECL is parsed as an initialization value, when its not actually part of that initiwlization value.""" pass
"""Abstract Handler with helper methods.""" from clang.cindex import CursorKind, TypeKind from ctypeslib.codegen import typedesc from ctypeslib.codegen.util import log_entity import logging log = logging.getLogger('handler') class CursorKindException(TypeError):
53
64
40
7
46
rviollette/ctypeslib
ctypeslib/codegen/handler.py
Python
CursorKindException
CursorKindException
12
16
12
13
f10a3c08f2156656db242989ce001c83182e63b7
bigcode/the-stack
train
dc70590e3ffb3ed1eef69429
train
class
class DuplicateDefinitionException(KeyError): """When we encounter a duplicate declaration/definition name.""" pass
class DuplicateDefinitionException(KeyError):
"""When we encounter a duplicate declaration/definition name.""" pass
(TypeError): """When a structure is invalid in the source code, sizeof, alignof returns negatives value. We detect it and do our best.""" pass class InvalidTranslationUnitException(TypeError): """When a translation unit is invalid""" pass class DuplicateDefinitionException(KeyError):
64
64
22
7
56
rviollette/ctypeslib
ctypeslib/codegen/handler.py
Python
DuplicateDefinitionException
DuplicateDefinitionException
32
35
32
33
ce47ae5ce508e3b51c4ff6d8f1fb20ad887074d3
bigcode/the-stack
train
cad5846682b6f11ee3b8ee46
train
class
class ClangHandler(object): """ Abstract class for handlers. """ def __init__(self, parser): self.parser = parser self._unhandled = [] def register(self, name, obj): return self.parser.register(name, obj) def get_registered(self, name): return self.parser.get_...
class ClangHandler(object):
""" Abstract class for handlers. """ def __init__(self, parser): self.parser = parser self._unhandled = [] def register(self, name, obj): return self.parser.register(name, obj) def get_registered(self, name): return self.parser.get_registered(name) def is_...
"""Abstract Handler with helper methods.""" from clang.cindex import CursorKind, TypeKind from ctypeslib.codegen import typedesc from ctypeslib.codegen.util import log_entity import logging log = logging.getLogger('handler') class CursorKindException(TypeError): """When a child node of a VAR_DECL is parsed as...
177
256
1,701
6
170
rviollette/ctypeslib
ctypeslib/codegen/handler.py
Python
ClangHandler
ClangHandler
40
232
40
41
f77b8628947c094a14002a730cbfbd8ccf61873e
bigcode/the-stack
train
5d5a160a21a1b6c1b575f084
train
class
class InvalidDefinitionError(TypeError): """When a structure is invalid in the source code, sizeof, alignof returns negatives value. We detect it and do our best.""" pass
class InvalidDefinitionError(TypeError):
"""When a structure is invalid in the source code, sizeof, alignof returns negatives value. We detect it and do our best.""" pass
.codegen.util import log_entity import logging log = logging.getLogger('handler') class CursorKindException(TypeError): """When a child node of a VAR_DECL is parsed as an initialization value, when its not actually part of that initiwlization value.""" pass class InvalidDefinitionError(TypeError):
64
64
41
7
56
rviollette/ctypeslib
ctypeslib/codegen/handler.py
Python
InvalidDefinitionError
InvalidDefinitionError
19
23
19
20
4cfd8da7841fd8476123315d0651af1b5bf622ab
bigcode/the-stack
train
96e53c0c5c57a008a0e51457
train
function
def stoch(s, nfastk=14, nfullk=3, nfulld=3): if not isinstance(s, DataFrame): s = DataFrame(dict(high=s, low=s, close=s)) hmax, lmin = hhv(s, nfastk), llv(s, nfastk) fastk = 100 * (s.close - lmin)/(hmax - lmin) fullk = moments.rolling_mean(fastk, nfullk) fulld = moments.rolling_mea...
def stoch(s, nfastk=14, nfullk=3, nfulld=3):
if not isinstance(s, DataFrame): s = DataFrame(dict(high=s, low=s, close=s)) hmax, lmin = hhv(s, nfastk), llv(s, nfastk) fastk = 100 * (s.close - lmin)/(hmax - lmin) fullk = moments.rolling_mean(fastk, nfullk) fulld = moments.rolling_mean(fullk, nfulld) return DataFrame(dict(...
aup = ema(up, n, wilder=True) emadn = ema(dn, n, wilder=True) return 100 * emaup/(emaup + emadn) def stoch(s, nfastk=14, nfullk=3, nfulld=3):
64
64
145
23
41
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
stoch
stoch
160
170
160
160
ded2a041449871c5fbed0a70aee03991b6c1975d
bigcode/the-stack
train
465a0e0f5b618e344521809a
train
function
def stochastic_oscillator_k(df): """Calculate stochastic oscillator %K for given data. :param df: pandas.DataFrame :return: pandas.DataFrame """ SOk = pd.Series((df['close'] - df['low']) / (df['high'] - df['low']), name='SO%k') df = df.join(SOk) return df
def stochastic_oscillator_k(df):
"""Calculate stochastic oscillator %K for given data. :param df: pandas.DataFrame :return: pandas.DataFrame """ SOk = pd.Series((df['close'] - df['low']) / (df['high'] - df['low']), name='SO%k') df = df.join(SOk) return df
pandas dataframe object :param period: periods for calculating SMA :return: a pandas series """ weights = np.repeat(1.0, period)/period sma = np.convolve(prices, weights, 'valid') return sma def stochastic_oscillator_k(df):
64
64
83
8
55
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
stochastic_oscillator_k
stochastic_oscillator_k
21
29
21
21
869818c79903537e5b21bba7e1c7992009479f08
bigcode/the-stack
train
fc5877b833d1e6585978bea0
train
function
def ichimoku(s, n1=9, n2=26, n3=52): conv = (hhv(s, n1) + llv(s, n1)) / 2 base = (hhv(s, n2) + llv(s, n2)) / 2 spana = (conv + base) / 2 spanb = (hhv(s, n3) + llv(s, n3)) / 2 return DataFrame(dict(conv=conv, base=base, spana=spana.shift(n2), spanb=spanb.shift(n2),...
def ichimoku(s, n1=9, n2=26, n3=52):
conv = (hhv(s, n1) + llv(s, n1)) / 2 base = (hhv(s, n2) + llv(s, n2)) / 2 spana = (conv + base) / 2 spanb = (hhv(s, n3) + llv(s, n3)) / 2 return DataFrame(dict(conv=conv, base=base, spana=spana.shift(n2), spanb=spanb.shift(n2), lspan=s.close.shift(-n2)))
+ 3*rocma3 + 4*rocma4) sig = moments.rolling_mean(kst, nsig) return DataFrame(dict(kst=kst, signal=sig)) def ichimoku(s, n1=9, n2=26, n3=52):
63
64
145
21
42
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
ichimoku
ichimoku
220
228
220
220
f255811eabf67d4f93c9cd11397d0868cff0d5cc
bigcode/the-stack
train
7f1f9b42ecf7de664707d0ba
train
function
def stochastic_oscillator_d(df, n): """Calculate stochastic oscillator %D for given data. :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ SOk = pd.Series((df['close'] - df['low']) / (df['high'] - df['low']), name='SO%k') SOd = pd.Series(SOk.ewm(span=n, min_periods=...
def stochastic_oscillator_d(df, n):
"""Calculate stochastic oscillator %D for given data. :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ SOk = pd.Series((df['close'] - df['low']) / (df['high'] - df['low']), name='SO%k') SOd = pd.Series(SOk.ewm(span=n, min_periods=n).mean(), name='SO%d') df = df....
:return: pandas.DataFrame """ SOk = pd.Series((df['close'] - df['low']) / (df['high'] - df['low']), name='SO%k') df = df.join(SOk) return df def stochastic_oscillator_d(df, n):
64
64
116
10
53
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
stochastic_oscillator_d
stochastic_oscillator_d
31
40
31
31
e8cd8d3caff006fd00b42472cfe97ebbe999640f
bigcode/the-stack
train
4eb8631fa2b656845d52ffff
train
function
def zigzag(s, pct=5): ut = 1 + pct / 100 dt = 1 - pct / 100 ld = s.index[0] lp = s.close[ld] tr = None zzd, zzp = [ld], [lp] for ix, ch, cl in zip(s.index, s.high, s.low): # No initial trend if tr is None: if ch / lp > ut: tr = 1 ...
def zigzag(s, pct=5):
ut = 1 + pct / 100 dt = 1 - pct / 100 ld = s.index[0] lp = s.close[ld] tr = None zzd, zzp = [ld], [lp] for ix, ch, cl in zip(s.index, s.high, s.low): # No initial trend if tr is None: if ch / lp > ut: tr = 1 elif cl / l...
@series_indicator('close') def gmma(s, nshort=[3, 5, 8, 10, 12, 15], nlong=[30, 35, 40, 45, 50, 60]): short = {str(n): ema(s, n) for n in nshort} long = {str(n): ema(s, n) for n in nlong} return DataFrame(short), DataFrame(long) def zigzag(s, pct=5):
108
108
361
9
99
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
zigzag
zigzag
368
419
368
368
3bf4fdfff849cb5df7a6810c3b85dc1efcab934e
bigcode/the-stack
train
fc3edf7c5fbb9431efc9cdde
train
function
def vortex(s, n=14): ss = s.shift(1) tr = s.high.combine(ss.close, max) - s.low.combine(ss.close, min) trn = moments.rolling_sum(tr, n) vmp = np.abs(s.high - ss.low) vmm = np.abs(s.low - ss.high) vip = moments.rolling_sum(vmp, n) / trn vin = moments.rolling_sum(vmm, n) / trn ...
def vortex(s, n=14):
ss = s.shift(1) tr = s.high.combine(ss.close, max) - s.low.combine(ss.close, min) trn = moments.rolling_sum(tr, n) vmp = np.abs(s.high - ss.low) vmm = np.abs(s.low - ss.high) vip = moments.rolling_sum(vmp, n) / trn vin = moments.rolling_sum(vmm, n) / trn return DataFrame(d...
, position, n=22, npen=3): if position == 'long': return hhv(s, n) - npen*atr(s, n) else: return llv(s, n) + npen*atr(s, n) def vortex(s, n=14):
64
64
118
8
56
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
vortex
vortex
344
356
344
344
3436c24bce7f1e5c5da861c9e114a0ade55928e4
bigcode/the-stack
train
f955158df1b45c31da298733
train
function
def sar(s, af=0.02, amax=0.2): high, low = s.high, s.low # Starting values sig0, xpt0, af0 = True, high[0], af sar = [low[0] - (high - low).std()] for i in range(1, len(s)): sig1, xpt1, af1 = sig0, xpt0, af0 lmin = min(low[i - 1], low[i]) lmax = max(high[i - 1],...
def sar(s, af=0.02, amax=0.2):
high, low = s.high, s.low # Starting values sig0, xpt0, af0 = True, high[0], af sar = [low[0] - (high - low).std()] for i in range(1, len(s)): sig1, xpt1, af1 = sig0, xpt0, af0 lmin = min(low[i - 1], low[i]) lmax = max(high[i - 1], high[i]) if sig1: ...
pen = moments.rolling_apply( sgn*s.diff(), nmean, lambda x: x[x > 0].mean() if (x > 0).any() else 0 ) stop = s + sgn*npen*pen return hhv(stop, nagg) if position == 'long' else llv(stop, nagg) def sar(s, af=0.02, amax=0.2):
97
97
324
17
80
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
sar
sar
278
314
278
278
5ed296833be4e3c74c9ad3dfa683d3edc6380709
bigcode/the-stack
train
a7ba9706c53d10ac6bf8a168
train
function
@series_indicator('close') def gmma(s, nshort=[3, 5, 8, 10, 12, 15], nlong=[30, 35, 40, 45, 50, 60]): short = {str(n): ema(s, n) for n in nshort} long = {str(n): ema(s, n) for n in nlong} return DataFrame(short), DataFrame(long)
@series_indicator('close') def gmma(s, nshort=[3, 5, 8, 10, 12, 15], nlong=[30, 35, 40, 45, 50, 60]):
short = {str(n): ema(s, n) for n in nshort} long = {str(n): ema(s, n) for n in nlong} return DataFrame(short), DataFrame(long)
(dict(vin=vin, vip=vip)) @series_indicator('close') def gmma(s, nshort=[3, 5, 8, 10, 12, 15], nlong=[30, 35, 40, 45, 50, 60]):
63
64
99
53
10
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
gmma
gmma
359
365
359
361
6d0e025fb30dc606936b4b7e644f47ff79b5e606
bigcode/the-stack
train
343383dcf927cd577c9c371d
train
function
@series_indicator('high') def hhv(s, n): return moments.rolling_max(s, n)
@series_indicator('high') def hhv(s, n):
return moments.rolling_max(s, n)
1) + [s[n - 1] + nf*sum(s[:n - 1])] for v in s[n:]: ws.append(v + ws[-1]*nf) return Series(ws, index=s.index) @series_indicator('high') def hhv(s, n):
64
64
23
13
51
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
hhv
hhv
107
109
107
108
647add825aa08ebea40656b813dcfe1ea8065bb6
bigcode/the-stack
train
66bd91c3f1ec35194cecbda0
train
function
def bollinger_bands(df, n, std, add_ave=True): """ :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ ave = df['close'].rolling(window=n, center=False).mean() sd = df['close'].rolling(window=n, center=False).std() upband = pd.Series(ave + (sd * std), name='bban...
def bollinger_bands(df, n, std, add_ave=True):
""" :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ ave = df['close'].rolling(window=n, center=False).mean() sd = df['close'].rolling(window=n, center=False).std() upband = pd.Series(ave + (sd * std), name='bband_upper_' + str(n)) dnband = pd.Series(ave ...
df['low']), name='SO%k') SOd = pd.Series(SOk.ewm(span=n, min_periods=n).mean(), name='SO%d') df = df.join(SOd) return df def bollinger_bands(df, n, std, add_ave=True):
64
64
196
16
47
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
bollinger_bands
bollinger_bands
42
59
42
42
10aa050b3774735c4d443b19a9b0c760191f6b87
bigcode/the-stack
train
0680b8317eef442ab6455fda
train
function
def adx(s, n=14): cs = s.close.shift(1) tr = s.high.combine(cs, max) - s.low.combine(cs, min) trs = _wilder_sum(tr, n) up = s.high - s.high.shift(1) dn = s.low.shift(1) - s.low pos = ((up > dn) & (up > 0)) * up neg = ((dn > up) & (dn > 0)) * dn dip = 100 * _wilder_sum(pos, ...
def adx(s, n=14):
cs = s.close.shift(1) tr = s.high.combine(cs, max) - s.low.combine(cs, min) trs = _wilder_sum(tr, n) up = s.high - s.high.shift(1) dn = s.low.shift(1) - s.low pos = ((up > dn) & (up > 0)) * up neg = ((dn > up) & (dn > 0)) * dn dip = 100 * _wilder_sum(pos, n) / trs din =...
0 if xpt0 < xpt1 else af1 sari = max(sari, lmax) else: af0 = af sari = xpt0 sar.append(sari) return Series(sar, index=s.index) def adx(s, n=14):
64
64
191
9
55
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
adx
adx
317
334
317
317
cdad43fa907fd858543ebb2e032f49592252646d
bigcode/the-stack
train
3e73ef6b2fb2cf105fb16da5
train
function
@series_indicator('close') def rsi(s, n=14): diff = s.diff() which_dn = diff < 0 up, dn = diff, diff*0 up[which_dn], dn[which_dn] = 0, -up[which_dn] emaup = ema(up, n, wilder=True) emadn = ema(dn, n, wilder=True) return 100 * emaup/(emaup + emadn)
@series_indicator('close') def rsi(s, n=14):
diff = s.diff() which_dn = diff < 0 up, dn = diff, diff*0 up[which_dn], dn[which_dn] = 0, -up[which_dn] emaup = ema(up, n, wilder=True) emadn = ema(dn, n, wilder=True) return 100 * emaup/(emaup + emadn)
: x.argmax()) / n dn = 100 * moments.rolling_apply(s.low, n + 1, lambda x: x.argmin()) / n return DataFrame(dict(up=up, down=dn)) @series_indicator('close') def rsi(s, n=14):
63
64
105
15
48
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
rsi
rsi
146
157
146
147
ecc583fbae5b5892969c9514e82eac683b5e8573
bigcode/the-stack
train
c4afe22eea620206e03a2c7a
train
function
@series_indicator('low') def llv(s, n): return moments.rolling_min(s, n)
@series_indicator('low') def llv(s, n):
return moments.rolling_min(s, n)
for v in s[n:]: ws.append(v + ws[-1]*nf) return Series(ws, index=s.index) @series_indicator('high') def hhv(s, n): return moments.rolling_max(s, n) @series_indicator('low') def llv(s, n):
64
64
23
13
51
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
llv
llv
112
114
112
113
8cf752838d03e52804c0f608bd289fce9a4fd44b
bigcode/the-stack
train
b6d9f51916497cbc42d8c5ea
train
function
@series_indicator('close') def macd(s, nfast=12, nslow=26, nsig=9, percent=True): fast, slow = ema(s, nfast), ema(s, nslow) if percent: macd = 100*(fast / slow - 1) else: macd = fast - slow sig = ema(macd, nsig) hist = macd - sig return DataFrame(dict(macd=macd, si...
@series_indicator('close') def macd(s, nfast=12, nslow=26, nsig=9, percent=True):
fast, slow = ema(s, nfast), ema(s, nslow) if percent: macd = 100*(fast / slow - 1) else: macd = fast - slow sig = ema(macd, nsig) hist = macd - sig return DataFrame(dict(macd=macd, signal=sig, hist=hist, fast=fast, slow=slow))
, n, wilder=False): span = n if not wilder else 2*n - 1 return moments.ewma(s, span=span) @series_indicator('close') def macd(s, nfast=12, nslow=26, nsig=9, percent=True):
64
64
121
29
35
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
macd
macd
123
136
123
124
8ba94d7107a115cbe99585b5594512543a0e70c3
bigcode/the-stack
train
62591ca55f5b25bcbceef970
train
function
@series_indicator('close') def ema(s, n, wilder=False): span = n if not wilder else 2*n - 1 return moments.ewma(s, span=span)
@series_indicator('close') def ema(s, n, wilder=False):
span = n if not wilder else 2*n - 1 return moments.ewma(s, span=span)
.index) @series_indicator('high') def hhv(s, n): return moments.rolling_max(s, n) @series_indicator('low') def llv(s, n): return moments.rolling_min(s, n) @series_indicator('close') def ema(s, n, wilder=False):
64
64
44
16
48
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
ema
ema
117
120
117
118
21b5de679b666b9335ee886a26b315d0a95a65f4
bigcode/the-stack
train
027c7c2b02e68262242c08e2
train
function
@series_indicator('close') def kst(s, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9): rocma1 = moments.rolling_mean(s / s.shift(r1) - 1, n1) rocma2 = moments.rolling_mean(s / s.shift(r2) - 1, n2) rocma3 = moments.rolling_mean(s / s.shift(r3) - 1, n3) rocma4 = moments.rolling_mean(s...
@series_indicator('close') def kst(s, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9):
rocma1 = moments.rolling_mean(s / s.shift(r1) - 1, n1) rocma2 = moments.rolling_mean(s / s.shift(r2) - 1, n2) rocma3 = moments.rolling_mean(s / s.shift(r3) - 1, n3) rocma4 = moments.rolling_mean(s / s.shift(r4) - 1, n4) kst = 100*(rocma1 + 2*rocma2 + 3*rocma3 + 4*rocma4) sig = moments.rol...
.close.diff()*s.volume, n) @series_indicator('close') def kst(s, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9):
64
64
207
56
8
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
kst
kst
207
217
207
208
d523d84150336b469bf7e275d08e2f8277e61a89
bigcode/the-stack
train
3f5b805b08c70740625da13f
train
function
def aroon(s, n=25): up = 100 * moments.rolling_apply(s.high, n + 1, lambda x: x.argmax()) / n dn = 100 * moments.rolling_apply(s.low, n + 1, lambda x: x.argmin()) / n return DataFrame(dict(up=up, down=dn))
def aroon(s, n=25):
up = 100 * moments.rolling_apply(s.high, n + 1, lambda x: x.argmax()) / n dn = 100 * moments.rolling_apply(s.low, n + 1, lambda x: x.argmin()) / n return DataFrame(dict(up=up, down=dn))
macd = fast - slow sig = ema(macd, nsig) hist = macd - sig return DataFrame(dict(macd=macd, signal=sig, hist=hist, fast=fast, slow=slow)) def aroon(s, n=25):
63
64
77
9
54
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
aroon
aroon
139
143
139
139
5affef31a1a4eb052abe46eba6a9537b50342714
bigcode/the-stack
train
9a2009900e92960cc3b6bb7b
train
function
def series_indicator(col): def inner_series_indicator(f): @wraps(f) def wrapper(s, *args, **kwargs): if isinstance(s, DataFrame): s = s[col] return f(s, *args, **kwargs) return wrapper return inner_series_indicator
def series_indicator(col):
def inner_series_indicator(f): @wraps(f) def wrapper(s, *args, **kwargs): if isinstance(s, DataFrame): s = s[col] return f(s, *args, **kwargs) return wrapper return inner_series_indicator
.Series(PosMF) TotMF = PP * df['volume'] MFR = pd.Series(PosMF / TotMF) MFI = pd.Series(MFR.rolling(n, min_periods=n).mean()) # df = df.join(MFI) return MFI def series_indicator(col):
64
64
64
5
58
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
series_indicator
series_indicator
84
92
84
84
910eb01678b532d163e4792181c9b1d031333e8b
bigcode/the-stack
train
33975e73836f92e073fe7a82
train
function
def money_flow_index(df, n): """Calculate Money Flow Index and Ratio for given data. :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ PP = (df['high'] + df['low'] + df['close']) / 3 i = 0 PosMF = [0] while i < df.index[-1]: if PP[i + 1] > PP[i]: ...
def money_flow_index(df, n):
"""Calculate Money Flow Index and Ratio for given data. :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ PP = (df['high'] + df['low'] + df['close']) / 3 i = 0 PosMF = [0] while i < df.index[-1]: if PP[i + 1] > PP[i]: PosMF.append(PP[i ...
bband_ave_' + str(n)) df = df.join(pd.concat([upband, dnband, ave], axis=1)) else: df = df.join(pd.concat([upband, dnband], axis=1)) return df def money_flow_index(df, n):
64
64
204
8
55
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
money_flow_index
money_flow_index
61
81
61
61
a41edf2860fad7adb173f7a245946853ab061ce2
bigcode/the-stack
train
ff45f0fd67d1dd652e9c7053
train
function
def force(s, n=2): return ema(s.close.diff()*s.volume, n)
def force(s, n=2):
return ema(s.close.diff()*s.volume, n)
, n=20): clv = (2*s.close - s.high - s.low) / (s.high - s.low) vol = s.volume return moments.rolling_sum(clv*vol, n) / moments.rolling_sum(vol, n) def force(s, n=2):
64
64
20
8
56
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
force
force
203
204
203
203
f8231b209ad0aab8af0f05cd1e5c3a5c97a4e726
bigcode/the-stack
train
4642b2c36591b2074aaa7dfd
train
function
def auto_envelope(s, nema=22, nsmooth=100, ndev=2.7): sema = ema(s.close, nema) mdiff = s[['high','low']].sub(sema, axis=0).abs().max(axis=1) csize = moments.ewmstd(mdiff, nsmooth)*ndev return DataFrame(dict(ema=sema, lenv=sema - csize, henv=sema + csize))
def auto_envelope(s, nema=22, nsmooth=100, ndev=2.7):
sema = ema(s.close, nema) mdiff = s[['high','low']].sub(sema, axis=0).abs().max(axis=1) csize = moments.ewmstd(mdiff, nsmooth)*ndev return DataFrame(dict(ema=sema, lenv=sema - csize, henv=sema + csize))
moments.rolling_sum(bp, n3) / moments.rolling_sum(tr, n3) return 100*(4*avg1 + 2*avg2 + avg3) / 7 def auto_envelope(s, nema=22, nsmooth=100, ndev=2.7):
64
64
105
22
41
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
auto_envelope
auto_envelope
243
248
243
243
ebc46765c2a994fd63cfb5c1aba8e896bf679c76
bigcode/the-stack
train
23f01a1de8f30e61226e45a8
train
function
@series_indicator('close') def dtosc(s, nrsi=13, nfastk=8, nfullk=5, nfulld=3): srsi = stoch(rsi(s, nrsi), nfastk, nfullk, nfulld) return DataFrame(dict(fast=srsi.fullk, slow=srsi.fulld))
@series_indicator('close') def dtosc(s, nrsi=13, nfastk=8, nfullk=5, nfulld=3):
srsi = stoch(rsi(s, nrsi), nfastk, nfullk, nfulld) return DataFrame(dict(fast=srsi.fullk, slow=srsi.fulld))
, nfulld) return DataFrame(dict(fastk=fastk, fullk=fullk, fulld=fulld)) @series_indicator('close') def dtosc(s, nrsi=13, nfastk=8, nfullk=5, nfulld=3):
63
64
79
34
29
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
dtosc
dtosc
173
176
173
174
15d274f92cf9d706ecac8bed5ceaaafa36515736
bigcode/the-stack
train
2cab789051b84ee3a94d097b
train
function
def cmf(s, n=20): clv = (2*s.close - s.high - s.low) / (s.high - s.low) vol = s.volume return moments.rolling_sum(clv*vol, n) / moments.rolling_sum(vol, n)
def cmf(s, n=20):
clv = (2*s.close - s.high - s.low) / (s.high - s.low) vol = s.volume return moments.rolling_sum(clv*vol, n) / moments.rolling_sum(vol, n)
(axis=1) mavg = moments.rolling_mean(s, n) mdev = moments.rolling_apply(s, n, lambda x: np.fabs(x - x.mean()).mean()) return (s - mavg)/(c * mdev) def cmf(s, n=20):
64
64
60
9
55
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
cmf
cmf
196
200
196
196
d49aedf39a907e608f0f20220a172ed662399ff5
bigcode/the-stack
train
c3b471bb2c17726593859ba1
train
function
def cci(s, n=20, c=0.015): if isinstance(s, DataFrame): s = s[['high', 'low', 'close']].mean(axis=1) mavg = moments.rolling_mean(s, n) mdev = moments.rolling_apply(s, n, lambda x: np.fabs(x - x.mean()).mean()) return (s - mavg)/(c * mdev)
def cci(s, n=20, c=0.015):
if isinstance(s, DataFrame): s = s[['high', 'low', 'close']].mean(axis=1) mavg = moments.rolling_mean(s, n) mdev = moments.rolling_apply(s, n, lambda x: np.fabs(x - x.mean()).mean()) return (s - mavg)/(c * mdev)
ld)) def atr(s, n=14): cs = s.close.shift(1) tr = s.high.combine(cs, max) - s.low.combine(cs, min) return ema(tr, n, wilder=True) def cci(s, n=20, c=0.015):
64
64
93
15
49
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
cci
cci
186
193
186
186
4f5dc9e0428cae00e00d58cf8ed2fc4e429ff478
bigcode/the-stack
train
72f4867bc04467d2ab014a03
train
function
def safezone(s, position, nmean=10, npen=2.0, nagg=3): if isinstance(s, DataFrame): s = s.low if position == 'long' else s.high sgn = -1.0 if position == 'long' else 1.0 # Compute the average upside/downside penetration pen = moments.rolling_apply( sgn*s.diff(), nmean, ...
def safezone(s, position, nmean=10, npen=2.0, nagg=3):
if isinstance(s, DataFrame): s = s.low if position == 'long' else s.high sgn = -1.0 if position == 'long' else 1.0 # Compute the average upside/downside penetration pen = moments.rolling_apply( sgn*s.diff(), nmean, lambda x: x[x > 0].mean() if (x > 0).any() else 0 ...
mavg + ndev*mstd lband = mavg - ndev*mstd return DataFrame(dict(ma=mavg, lband=lband, hband=hband)) def safezone(s, position, nmean=10, npen=2.0, nagg=3):
63
64
156
24
39
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
safezone
safezone
262
275
262
262
9d434e7e4600d417ad9c41e2fab0ed801ae61050
bigcode/the-stack
train
4fd87570401c01e76031dd17
train
function
def atr(s, n=14): cs = s.close.shift(1) tr = s.high.combine(cs, max) - s.low.combine(cs, min) return ema(tr, n, wilder=True)
def atr(s, n=14):
cs = s.close.shift(1) tr = s.high.combine(cs, max) - s.low.combine(cs, min) return ema(tr, n, wilder=True)
k=5, nfulld=3): srsi = stoch(rsi(s, nrsi), nfastk, nfullk, nfulld) return DataFrame(dict(fast=srsi.fullk, slow=srsi.fulld)) def atr(s, n=14):
63
64
46
8
55
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
atr
atr
179
183
179
179
3473b7e3f8d3f2470a469ba3690dc37e140336d3
bigcode/the-stack
train
de254430b6772740fe20d221
train
function
def _wilder_sum(s, n): s = s.dropna() nf = (n - 1) / n ws = [np.nan]*(n - 1) + [s[n - 1] + nf*sum(s[:n - 1])] for v in s[n:]: ws.append(v + ws[-1]*nf) return Series(ws, index=s.index)
def _wilder_sum(s, n):
s = s.dropna() nf = (n - 1) / n ws = [np.nan]*(n - 1) + [s[n - 1] + nf*sum(s[:n - 1])] for v in s[n:]: ws.append(v + ws[-1]*nf) return Series(ws, index=s.index)
_indicator(f): @wraps(f) def wrapper(s, *args, **kwargs): if isinstance(s, DataFrame): s = s[col] return f(s, *args, **kwargs) return wrapper return inner_series_indicator def _wilder_sum(s, n):
64
64
88
9
54
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
_wilder_sum
_wilder_sum
95
104
95
95
397ca8b49429452c726fd231e8d91e2485ebb34d
bigcode/the-stack
train
c098bc96984b80f1ba3a512d
train
function
def simple_moving_average(prices, period=26): """ :param df: pandas dataframe object :param period: periods for calculating SMA :return: a pandas series """ weights = np.repeat(1.0, period)/period sma = np.convolve(prices, weights, 'valid') return sma
def simple_moving_average(prices, period=26):
""" :param df: pandas dataframe object :param period: periods for calculating SMA :return: a pandas series """ weights = np.repeat(1.0, period)/period sma = np.convolve(prices, weights, 'valid') return sma
# -*- coding: utf-8 -*- from __future__ import division from functools import wraps import numpy as np from pandas import DataFrame, Series from pandas.stats import moments import pandas as pd def simple_moving_average(prices, period=26):
57
64
75
12
44
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
simple_moving_average
simple_moving_average
11
19
11
11
56f7b38edd639a8d9facb73598e5fafbda6c05a3
bigcode/the-stack
train
f858c3342bf20ff78debb088
train
function
def chandelier(s, position, n=22, npen=3): if position == 'long': return hhv(s, n) - npen*atr(s, n) else: return llv(s, n) + npen*atr(s, n)
def chandelier(s, position, n=22, npen=3):
if position == 'long': return hhv(s, n) - npen*atr(s, n) else: return llv(s, n) + npen*atr(s, n)
dx = 100 * np.abs((dip - din)/(dip + din)) adx = ema(dx, n, wilder=True) return DataFrame(dict(adx=adx, dip=dip, din=din)) def chandelier(s, position, n=22, npen=3):
63
64
59
15
48
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
chandelier
chandelier
337
341
337
337
610ca374bc581371d20e2a84e4cd6f05c33b54c5
bigcode/the-stack
train
9b4050655b63f217e64600ad
train
function
@series_indicator('close') def bbands(s, n=20, ndev=2): mavg = moments.rolling_mean(s, n) mstd = moments.rolling_std(s, n) hband = mavg + ndev*mstd lband = mavg - ndev*mstd return DataFrame(dict(ma=mavg, lband=lband, hband=hband))
@series_indicator('close') def bbands(s, n=20, ndev=2):
mavg = moments.rolling_mean(s, n) mstd = moments.rolling_std(s, n) hband = mavg + ndev*mstd lband = mavg - ndev*mstd return DataFrame(dict(ma=mavg, lband=lband, hband=hband))
moments.ewmstd(mdiff, nsmooth)*ndev return DataFrame(dict(ema=sema, lenv=sema - csize, henv=sema + csize)) @series_indicator('close') def bbands(s, n=20, ndev=2):
63
64
87
20
43
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
bbands
bbands
251
259
251
252
38373f56d7167e28aaabd27341d042b027716195
bigcode/the-stack
train
00e8fec4b9e07dff2db3fac8
train
function
def ultimate(s, n1=7, n2=14, n3=28): cs = s.close.shift(1) bp = s.close - s.low.combine(cs, min) tr = s.high.combine(cs, max) - s.low.combine(cs, min) avg1 = moments.rolling_sum(bp, n1) / moments.rolling_sum(tr, n1) avg2 = moments.rolling_sum(bp, n2) / moments.rolling_sum(tr, n2) avg3 = ...
def ultimate(s, n1=7, n2=14, n3=28):
cs = s.close.shift(1) bp = s.close - s.low.combine(cs, min) tr = s.high.combine(cs, max) - s.low.combine(cs, min) avg1 = moments.rolling_sum(bp, n1) / moments.rolling_sum(tr, n1) avg2 = moments.rolling_sum(bp, n2) / moments.rolling_sum(tr, n2) avg3 = moments.rolling_sum(bp, n3) / moments....
2 return DataFrame(dict(conv=conv, base=base, spana=spana.shift(n2), spanb=spanb.shift(n2), lspan=s.close.shift(-n2))) def ultimate(s, n1=7, n2=14, n3=28):
63
64
151
19
44
Rinuys/RLTradingBot
tf_deep_rl_trader/ta.py
Python
ultimate
ultimate
231
240
231
231
e6c640811d3bdefbce2b02587539b789f4e4ee21
bigcode/the-stack
train
5253850c335ba2be6c2566d6
train
class
class looper(object): """ Helper for looping (particularly in templates) Use this like:: for loop, item in looper(seq): if loop.first: ... """ def __init__(self, seq): self.seq = seq def __iter__(self): return looper_iter(self.seq) def...
class looper(object):
""" Helper for looping (particularly in templates) Use this like:: for loop, item in looper(seq): if loop.first: ... """ def __init__(self, seq): self.seq = seq def __iter__(self): return looper_iter(self.seq) def __repr__(self): ...
', 'b', 'c']): ... print loop.number, item ... if not loop.last: ... print '---' 1 a --- 2 b --- 3 c """ __all__ = ['looper'] class looper(object):
64
64
98
5
59
jyotijaya/pyspec
pyspec/tempita/_looper.py
Python
looper
looper
23
42
23
23
814de47f8023b7b80dda9c4b60d112d10ed05aab
bigcode/the-stack
train
7dba5604690654bbc4b3afbd
train
class
class looper_iter(object): def __init__(self, seq): self.seq = list(seq) self.pos = 0 def __iter__(self): return self def next(self): if self.pos >= len(self.seq): raise StopIteration result = loop_pos(self.seq, self.pos), self.seq[self.pos] sel...
class looper_iter(object):
def __init__(self, seq): self.seq = list(seq) self.pos = 0 def __iter__(self): return self def next(self): if self.pos >= len(self.seq): raise StopIteration result = loop_pos(self.seq, self.pos), self.seq[self.pos] self.pos += 1 return re...
def __init__(self, seq): self.seq = seq def __iter__(self): return looper_iter(self.seq) def __repr__(self): return '<%s for %r>' % ( self.__class__.__name__, self.seq) class looper_iter(object):
64
64
86
6
58
jyotijaya/pyspec
pyspec/tempita/_looper.py
Python
looper_iter
looper_iter
44
58
44
45
2f113152c526402fb2f1202c56c185a0e3388f9b
bigcode/the-stack
train
b85d2c793eacb8766cb53f96
train
class
class loop_pos(object): def __init__(self, seq, pos): self.seq = seq self.pos = pos def __repr__(self): return '<loop pos=%r at %r>' % ( self.seq[pos], pos) def index(self): return self.pos index = property(index) def number(self): return self....
class loop_pos(object):
def __init__(self, seq, pos): self.seq = seq self.pos = pos def __repr__(self): return '<loop pos=%r at %r>' % ( self.seq[pos], pos) def index(self): return self.pos index = property(index) def number(self): return self.pos + 1 number = prop...
in templates) Use this like:: for loop, item in looper(seq): if loop.first: ... """ def __init__(self, seq): self.seq = seq def __iter__(self): return looper_iter(self.seq) def __repr__(self): return '<%s for %r>' % ( self...
176
176
588
5
170
jyotijaya/pyspec
pyspec/tempita/_looper.py
Python
loop_pos
loop_pos
60
151
60
61
27c22682ab42c480eb01ec25314437ac04e539a1
bigcode/the-stack
train
e6ada297baf39bf9566e0fa4
train
function
def ficha(jog='desconhecido', gols=0): """ --> cadastra jogador e numero de gols :param jog: nome do jogador, OPCIONAL. Default = 'desconhecido' :param gols: qtdade de gols, OPCIONAL. Default = 0 :return: nome e qtdade de gols """ jog = str(input('nome do jogador: ')) gols = inpu...
def ficha(jog='desconhecido', gols=0):
""" --> cadastra jogador e numero de gols :param jog: nome do jogador, OPCIONAL. Default = 'desconhecido' :param gols: qtdade de gols, OPCIONAL. Default = 0 :return: nome e qtdade de gols """ jog = str(input('nome do jogador: ')) gols = input('qtdade de gols: ') if jog.isalph...
# FUNCOES def ficha(jog='desconhecido', gols=0):
19
64
160
14
4
fblaz/Python-ex---curso-em-video
ex103 - funcao jogador.py
Python
ficha
ficha
3
21
3
3
314fa6c4ea32f81aa8750129e763208e127aad58
bigcode/the-stack
train
8c8adb97069fd39ea1c3b713
train
class
class V1alpha1OperationInitiator(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attri...
class V1alpha1OperationInitiator(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ Consolidate Services Description of all APIs # noqa: E501 The version of the OpenAPI document: version not set Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from argocd_client.configuration import Configuration class V1alpha...
84
256
922
10
73
thepabloaguilar/argocd-client
argocd_client/models/v1alpha1_operation_initiator.py
Python
V1alpha1OperationInitiator
V1alpha1OperationInitiator
21
150
21
21
f648cb50c478f24c296c54aa67205732a6d86036
bigcode/the-stack
train
ec474bf6df0d06f3bb06c8f8
train
class
class FilesTest(unittest.TestCase): @staticmethod def make_request(path_str): return wsgi_apps.Request( environ={'PATH_INFO': path_str}, context=contexts.Context() ) def test_get_local_path(self): dir_path = Path(__file__).parent.parent.resolve() self.assertEqua...
class FilesTest(unittest.TestCase): @staticmethod
def make_request(path_str): return wsgi_apps.Request( environ={'PATH_INFO': path_str}, context=contexts.Context() ) def test_get_local_path(self): dir_path = Path(__file__).parent.parent.resolve() self.assertEqual( files.get_local_path( se...
import unittest import unittest.mock from pathlib import Path from g1.asyncs import kernels from g1.bases import contexts from g1.webs import consts from g1.webs import wsgi_apps from g1.webs.handlers import etags from g1.webs.handlers import files class FilesTest(unittest.TestCase): @staticmethod
77
79
266
11
65
clchiou/garage
py/g1/webs/tests/test_files.py
Python
FilesTest
FilesTest
14
50
14
16
84bf510a88089faab8c4eb2612ca493c5a6e1bd4
bigcode/the-stack
train
aa3ea04c77e107a8d0b7d396
train
class
class HandlerTest(unittest.TestCase): DIR_PATH = Path(__file__).parent.parent.resolve() def setUp(self): super().setUp() self.request = None self.response = None self.handler = None def assert_request(self, context): self.assertEqual(self.request.context.asdict(), ...
class HandlerTest(unittest.TestCase):
DIR_PATH = Path(__file__).parent.parent.resolve() def setUp(self): super().setUp() self.request = None self.response = None self.handler = None def assert_request(self, context): self.assertEqual(self.request.context.asdict(), context) def assert_response(self,...
): return wsgi_apps.Request( environ={'PATH_INFO': path_str}, context=contexts.Context() ) def test_get_local_path(self): dir_path = Path(__file__).parent.parent.resolve() self.assertEqual( files.get_local_path( self.make_request('//.//./tests...
256
256
1,641
7
249
clchiou/garage
py/g1/webs/tests/test_files.py
Python
HandlerTest
HandlerTest
53
261
53
54
8aadbeb6236859ea3648c30069559ebadda7874a
bigcode/the-stack
train
3d92fa9f115faf2bec9f246d
train
class
class StockEnvTrade(gym.Env): """A stock trading environment for OpenAI gym""" metadata = {'render.modes': ['human']} def __init__(self, df, day=0, turbulence_threshold=140, initial=True, previous_state=[], model_name='', iteration=''): # super(StockEnv, self).__init__() # money = 10 , scop...
class StockEnvTrade(gym.Env):
"""A stock trading environment for OpenAI gym""" metadata = {'render.modes': ['human']} def __init__(self, df, day=0, turbulence_threshold=140, initial=True, previous_state=[], model_name='', iteration=''): # super(StockEnv, self).__init__() # money = 10 , scope = 1 self.day = day ...
import numpy as np import pandas as pd from gym.utils import seeding import gym from gym import spaces import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from config import config as config class StockEnvTrade(gym.Env):
55
256
2,571
8
46
19910101bacon/finRL
env/EnvMultipleStock_trade.py
Python
StockEnvTrade
StockEnvTrade
12
242
12
12
578adbea01717cd5524d7843a9da5cf49f898321
bigcode/the-stack
train
36646767d26ac416a7126fae
train
function
def bigfind(word, embeddings, expected_facet=None): if expected_facet == None: for n in sorted(embeddings): find(word, embeddings[n], n) else: for n in sorted (embeddings): if n == expected_facet: find (word, embeddings[n], n)
def bigfind(word, embeddings, expected_facet=None):
if expected_facet == None: for n in sorted(embeddings): find(word, embeddings[n], n) else: for n in sorted (embeddings): if n == expected_facet: find (word, embeddings[n], n)
(), key=lambda x:x[1], reverse=True) for i in range(10): (k,v) = sorted_x[i] print (f"{k}\t{v:.3f}") print () # find closest terms for all states def bigfind(word, embeddings, expected_facet=None):
64
64
66
12
51
sandeepsoni/jca_release
scripts/findNearest.py
Python
bigfind
bigfind
33
40
33
33
5c0091e192a5186627067018b1e513a746f35016
bigcode/the-stack
train
95ff2760107707bcf099322a
train
function
def find(word, data, name): print (f"Finding: {word} in {name}") scores={} if word not in data: print (f"{word} not in vocab") return a=data[word] for word2 in data: try: score=np.inner(a, data[word2]) scores[word2]=score except: pass sorted_x = sorted(scores.items(), key=lambda x:x[1], reverse...
def find(word, data, name):
print (f"Finding: {word} in {name}") scores={} if word not in data: print (f"{word} not in vocab") return a=data[word] for word2 in data: try: score=np.inner(a, data[word2]) scores[word2]=score except: pass sorted_x = sorted(scores.items(), key=lambda x:x[1], reverse=True) for i in range(10): ...
learned word embeddings in sys.argv[1] in memory; for a given search term q, find the 10 closest terms to q in each of the 51 states. """ import sys,math,operator import numpy as np from numpy import linalg as LA def find(word, data, name):
64
64
132
8
55
sandeepsoni/jca_release
scripts/findNearest.py
Python
find
find
11
30
11
11
8b2acd6299d0ad4e954c3070883fba2dd10bf46f
bigcode/the-stack
train
959626bd2fd198ed71cb790f
train
function
def normalize(embeddings): for name in embeddings: for word in embeddings[name]: a=embeddings[name][word] norm=LA.norm(a, 2) a /= norm embeddings[name][word]=a
def normalize(embeddings):
for name in embeddings: for word in embeddings[name]: a=embeddings[name][word] norm=LA.norm(a, 2) a /= norm embeddings[name][word]=a
None: for n in sorted(embeddings): find(word, embeddings[n], n) else: for n in sorted (embeddings): if n == expected_facet: find (word, embeddings[n], n) # normalize vectors for faster cosine similarity calculation def normalize(embeddings):
64
64
53
6
57
sandeepsoni/jca_release
scripts/findNearest.py
Python
normalize
normalize
43
50
43
43
9a512e3fb36b410fe196c69540759b6fb374387e
bigcode/the-stack
train
60987aa718d5d956285037d8
train
function
def getFacets(filename): file=open(filename) facets={} for i,line in enumerate (file): if i > 0: cols=line.rstrip().split(" ") facets[cols[0]]=1 file.close() # don't count the base facet #del facets["MAIN"] return facets.keys()
def getFacets(filename):
file=open(filename) facets={} for i,line in enumerate (file): if i > 0: cols=line.rstrip().split(" ") facets[cols[0]]=1 file.close() # don't count the base facet #del facets["MAIN"] return facets.keys()
embeddings): for name in embeddings: for word in embeddings[name]: a=embeddings[name][word] norm=LA.norm(a, 2) a /= norm embeddings[name][word]=a # get all active facets in embeddings def getFacets(filename):
64
64
71
6
57
sandeepsoni/jca_release
scripts/findNearest.py
Python
getFacets
getFacets
53
66
53
53
2f26b460511177a9bf968c8d877cd9f391d35dce
bigcode/the-stack
train
e25927860ada6ab491bf1f1e
train
function
def process(filename, expected_facet=None): file=open(filename) embeddings={} facets=getFacets(filename) # if you want to only consider a few metadata facets and not all 51 states, do that here. e.g.: # facets=["MA", "PA"] for facet in facets: embeddings[facet]={} for line in file: cols=line.rstrip()....
def process(filename, expected_facet=None):
file=open(filename) embeddings={} facets=getFacets(filename) # if you want to only consider a few metadata facets and not all 51 states, do that here. e.g.: # facets=["MA", "PA"] for facet in facets: embeddings[facet]={} for line in file: cols=line.rstrip().split(" ") if len(cols) < 10: continue ...
=LA.norm(a, 2) a /= norm embeddings[name][word]=a # get all active facets in embeddings def getFacets(filename): file=open(filename) facets={} for i,line in enumerate (file): if i > 0: cols=line.rstrip().split(" ") facets[cols[0]]=1 file.close() # don't count the base facet #del facets["MAIN"] ...
111
111
371
9
102
sandeepsoni/jca_release
scripts/findNearest.py
Python
process
process
68
127
68
68
eb4aa22a82b8bc0e1d8c87c469c29dda9a6ace6f
bigcode/the-stack
train
66c3e913c84db7039c4113ad
train
class
class UnetSkipConnectionInnerRandomBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, inner_ap_nc, input_nc=None, ...
class UnetSkipConnectionInnerRandomBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, inner_ap_nc, input_nc=None, submodule=None, outermost=False, innermost=False,...
-- if this module is the innermost module norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. """ super(DisperseBlock, self).__init__() self.outermost = outermost if type(norm_layer) == functools.partial: use_bias ...
256
256
881
11
245
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
UnetSkipConnectionInnerRandomBlock
UnetSkipConnectionInnerRandomBlock
430
518
430
430
39d72f36bd62df1c40771971631881e3c8917c19
bigcode/the-stack
train
9c0e9c53797b2c1491296ab5
train
class
class MaskCollectionGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channe...
class MaskCollectionGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (...
=norm_layer) # add the outermost UNet layer self.model = DisperseBlock(output_nc, ngf, net_branch_num, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer def forward(self, input): """Standard forward""" return self.model(input) class ...
87
87
293
7
80
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
MaskCollectionGenerator
MaskCollectionGenerator
109
131
109
109
458484331c71d96aa3ccadc8fa598fea46330c04
bigcode/the-stack
train
74298c8eedf14aff0c9e2c42
train
class
class PostMaskUnetGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels...
class PostMaskUnetGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (...
_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=net_branch_num, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost UNet layer self.m...
180
180
600
9
171
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
PostMaskUnetGenerator
PostMaskUnetGenerator
76
106
76
76
3aa10f75848ccfef011978de5090e4094e6d7e86
bigcode/the-stack
train
62c38515f2aed7a4e51b3713
train
class
class MultiCNNMaskRandomBGBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submod...
class MultiCNNMaskRandomBGBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None, outermost=False, innermost=False, ...
nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc mask_models = [] for i in range(0, branch_num): equalconv = nn.Conv2d(input_nc, inner_nc, kernel_size=3 + 2 * i, ...
256
256
1,033
10
246
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
MultiCNNMaskRandomBGBlock
MultiCNNMaskRandomBGBlock
222
315
222
222
5fe69b6973f6149a7c4be600cf15dc32b3b56860
bigcode/the-stack
train
b83558a9bf3a93ad0829412b
train
class
class UnetInnerRandomGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, inner_ap_nc=0, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels...
class UnetInnerRandomGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, inner_ap_nc=0, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int...
|num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer We construct the U-Net from the innermost layer to the outermost la...
180
180
603
9
171
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
UnetInnerRandomGenerator
UnetInnerRandomGenerator
134
164
134
134
97be0a9e2954a27e0dea7b4e2e76e88f771e54d1
bigcode/the-stack
train
04fdb1031b91b72b0b3d7b7e
train
class
class UnetRandomAndMaskGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of cha...
class UnetRandomAndMaskGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (...
submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=ngf * net_branch_num, submodule=unet_block, outermost=True, norm_layer=norm_layer) #...
185
185
618
10
175
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
UnetRandomAndMaskGenerator
UnetRandomAndMaskGenerator
43
73
43
43
0c35b4f4c0f575c2407d20f09db8fe21bd6f4a32
bigcode/the-stack
train
b055447a5e7bb06bbf0c0850
train
class
class LabelBranchGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, inpu...
class LabelBranchGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn....
/ 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] upsam_branch_model +...
148
148
494
7
141
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
LabelBranchGenerator
LabelBranchGenerator
625
667
625
625
0f5a3b865aa2f956c8e4483094c049a9321d0fe3
bigcode/the-stack
train
1523f61d2c3d075e2204eae6
train
class
class UpsamplingResnetBranchGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__...
class UpsamplingResnetBranchGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn....
add downsampling layers mult = 2 ** i comp_model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2 ** n_downsampling for i in range(pre_n_...
176
176
589
10
166
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
UpsamplingResnetBranchGenerator
UpsamplingResnetBranchGenerator
572
622
572
572
7dd5148b0896bc3d4fad8f30d7a8564a07de0dc2
bigcode/the-stack
train
39ecfcca7bb75356b9f364ee
train
class
class MaskCollectionBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=No...
class MaskCollectionBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None, outermost=False, innermost=False, ...
processed_y.shape[3] - 1 - cut_width src_pos_x = random.randint(0, upper_bound) src_pos_x = src_pos_x - src_pos_x % controlling_stick_gap src_pos_y = random.randint(0, upper_bound) tag_pos_x = random.randint(0, upper_bound - int(controlling_stick_gap / 2)) tag_pos_x = tag_pos_x...
197
197
659
7
189
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
MaskCollectionBlock
MaskCollectionBlock
318
381
318
318
bfbcee96265552087063b1ac57d418b2541f503a
bigcode/the-stack
train
e3b5ba6c8240cc1a7acfffa1
train
class
class UnetAttentionMaskGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of cha...
class UnetAttentionMaskGenerator(nn.Module):
"""Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, net_branch_num=3, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (...
import random import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler from models.base_networks import * class UnetAttentionMaskGenerator(nn.Module):
44
182
609
9
35
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
UnetAttentionMaskGenerator
UnetAttentionMaskGenerator
10
40
10
10
0941eaa019ac0e2d436d6a34f11a2822a4379792
bigcode/the-stack
train
2b623a424cdd9c331dc28bde
train
class
class DownsamplingResnetBranchGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init...
class DownsamplingResnetBranchGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn....
self.model_up = nn.Sequential(*model_up) def forward(self, x, inner_ap): if self.outermost: down_out = self.model_down(x) sub_out = self.model_sub(down_out, inner_ap) return self.model_up(sub_out) elif self.innermost: down_out = self.model_dow...
165
165
550
10
155
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
DownsamplingResnetBranchGenerator
DownsamplingResnetBranchGenerator
521
569
521
521
d2819020088d2142afff021e4748fd59ccbb7947
bigcode/the-stack
train
f867a193e085bb7de1bcbb7d
train
class
class LeakReluResnetGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, i...
class LeakReluResnetGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn....
sampling n_downsampling_to_one = 7 - n_downsampling hight_delta_branch_model = [] input_chanel = ngf * mult for i in range(n_downsampling_to_one): # add downsampling layers hight_delta_branch_model += [nn.Conv2d(input_chanel, output_nc, kernel_size=3, stride=2, padding=1, bi...
207
207
691
10
197
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
LeakReluResnetGenerator
LeakReluResnetGenerator
670
728
670
670
3b8c3da5a7c7d3ce46b7b4b04db0a6dd2061cbb0
bigcode/the-stack
train
85da69df7d4338e020b538d3
train
class
class MultiCNNMaskBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None...
class MultiCNNMaskBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None, outermost=False, innermost=False, ...
, ngf * 4, inner_ap_nc, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionInnerRandomBlock(ngf, ngf * 2, inner_ap_nc, input_nc=None, submodule=unet_block, norm_layer=norm_layer) self.model = UnetSkipConnectionInnerRandomBlock(output_nc, ngf, inner_ap_nc, input_nc...
154
154
515
8
146
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
MultiCNNMaskBlock
MultiCNNMaskBlock
167
219
167
167
d4e0ccd865192a841f67f1d1e746d6d43f898f82
bigcode/the-stack
train
db4e72d61e9632fd5bca4084
train
class
class DisperseBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None, ou...
class DisperseBlock(nn.Module):
"""Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, branch_num, input_nc=None, submodule=None, outermost=False, innermost=False, ...
, shrinkrelu] self.shrinkpart = nn.Sequential(*shrinkpart) def forward(self, x, mask, random_bg): mask_y = None for mask_model in self.mask_models: mask_y_branch = mask_model(x) * mask if mask_y is None: mask_y = mask_y_branch else: ...
132
132
442
8
123
KingOnTheStar/pytorch-CycleGAN-and-pix2pix
models/experimental_networks.py
Python
DisperseBlock
DisperseBlock
384
427
384
384
a6be945176367dd9cd67e03134b673c6851e019f
bigcode/the-stack
train
42688df5109c59c1dece2ca8
train
class
class QNetwork_pixel(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action ...
class QNetwork_pixel(nn.Module):
"""Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed ...
seed fc1_units (int): Number of nodes in first hidden layer fc2_units (int): Number of nodes in second hidden layer """ super(QNetwork, self).__init__() self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(state_size, fc1_units) self.fc2 = nn.Linear(f...
148
149
499
7
141
StefanThaenert/deep-reinforcement-learning
1_07_p1_navigation/model.py
Python
QNetwork_pixel
QNetwork_pixel
32
78
32
32
6fbeb4de2c4d9f4c02f5b90964395803901c5bfe
bigcode/the-stack
train
01d063d23f675f677d8e0b92
train
class
class QNetwork(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=16): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of...
class QNetwork(nn.Module):
"""Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=16): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action se...
import torch import torch.nn as nn import torch.nn.functional as F class QNetwork(nn.Module):
22
67
224
6
15
StefanThaenert/deep-reinforcement-learning
1_07_p1_navigation/model.py
Python
QNetwork
QNetwork
5
28
5
5
05bec6ffccd74c598991ccbda3000f69a85f3011
bigcode/the-stack
train
ca8dff020afed825a1744176
train
class
class Targeter: def __init__( self, target: Ephemeris, solutions: Mapping[str, Callable] = None, target_radius: Optional[float] = None, ): """ target: LHorizon instance or dataframe; if a dataframe, must have columns named 'ra, dec, dist', 'az, alt, di...
class Targeter:
def __init__( self, target: Ephemeris, solutions: Mapping[str, Callable] = None, target_radius: Optional[float] = None, ): """ target: LHorizon instance or dataframe; if a dataframe, must have columns named 'ra, dec, dist', 'az, alt, dist', or 'x, y, z...
from collections.abc import Callable, Mapping from typing import Optional, Union import warnings import numpy as np import pandas as pd from lhorizon import LHorizon from lhorizon._type_aliases import Ephemeris from lhorizon.lhorizon_utils import sph2cart, hats, time_series_to_et from lhorizon.solutions import make_r...
100
256
2,464
4
95
Kevin-Mattheus-Moerman/lhorizon
lhorizon/target.py
Python
Targeter
Targeter
15
285
15
15
0fa7bc1a24d5c2b2b119ab49ae246a19d27b3f74
bigcode/the-stack
train
189c99bd1add39465d4442c0
train
function
def calculate_elo( player_1_points: int, player_2_points: int, draw: bool = False, ) -> typing.Tuple[int, int]: """Returns elo changes for given players. player_1 is supposed to be the winner. As K is 50, maximum returned value is 50 and -50.""" if draw: win = 0.5 loss = 0.5...
def calculate_elo( player_1_points: int, player_2_points: int, draw: bool = False, ) -> typing.Tuple[int, int]:
"""Returns elo changes for given players. player_1 is supposed to be the winner. As K is 50, maximum returned value is 50 and -50.""" if draw: win = 0.5 loss = 0.5 else: win = 1 loss = 0 expected_score_player_1 = ( 1 / (1 + 10 ** ((player_2_points - play...
MatchParticipant.query.filter( RunningMatchParticipant.match_id == match_id ).delete() if commit_db: db.session.commit() def calculate_elo( player_1_points: int, player_2_points: int, draw: bool = False, ) -> typing.Tuple[int, int]:
65
65
219
36
29
HealYouDown/flo-league
app/blueprints/moderating/utils.py
Python
calculate_elo
calculate_elo
26
52
26
30
45dd9baf931d514c6c7c7686ff9e85538bb62e36
bigcode/the-stack
train
06e441a1fea3c773a2e990bf
train
function
def delete_match( match_id: int, commit_db: bool = True, ) -> None: # Delete matches RunningMatch.query.filter( RunningMatch.id == match_id, ).delete() # Delete participants RunningMatchParticipant.query.filter( RunningMatchParticipant.match_id == match_id ).delete() ...
def delete_match( match_id: int, commit_db: bool = True, ) -> None: # Delete matches
RunningMatch.query.filter( RunningMatch.id == match_id, ).delete() # Delete participants RunningMatchParticipant.query.filter( RunningMatchParticipant.match_id == match_id ).delete() if commit_db: db.session.commit()
import typing from app.extensions import db from app.models import RunningMatch, RunningMatchParticipant from app.constants import K def delete_match( match_id: int, commit_db: bool = True, ) -> None: # Delete matches
53
64
81
27
25
HealYouDown/flo-league
app/blueprints/moderating/utils.py
Python
delete_match
delete_match
8
23
8
12
2f651d9264877a77ada78e923fdc048612768657
bigcode/the-stack
train
e4311fdb885ec2fefc609910
train
class
class FormRecognizerClient(FormRecognizerClientBaseAsync): """FormRecognizerClient extracts information from forms and images into structured data. It is the interface to use for analyzing receipts, business cards, invoices, recognizing content/layout from forms, and analyzing custom forms from trained mode...
class FormRecognizerClient(FormRecognizerClientBaseAsync):
"""FormRecognizerClient extracts information from forms and images into structured data. It is the interface to use for analyzing receipts, business cards, invoices, recognizing content/layout from forms, and analyzing custom forms from trained models. It provides different methods based on inputs from ...
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ # pylint: disable=protected-access from typing import Any, IO, Union, List from azure.core.tracing.decorator_async import distributed_trace_async from a...
175
256
7,384
10
164
mohamedshabanofficial/azure-sdk-for-python
sdk/formrecognizer/azure-ai-formrecognizer/azure/ai/formrecognizer/aio/_form_recognizer_client_async.py
Python
FormRecognizerClient
FormRecognizerClient
25
709
25
25
40fb80a400fada339b078f1d5a34a9ae45ac95e6
bigcode/the-stack
train
57c162312cfc512688743e23
train
function
@app.route('/delete', methods=['GET', 'POST']) def delete(): if request.method == 'GET': # View return render_template('index.html', pads=KEY.pads, del_mode=True) else: # POST pad_id = request.form.getlist('pad_id')[0] KEY.del_pad(pad_id) return redirect('/delete...
@app.route('/delete', methods=['GET', 'POST']) def delete():
if request.method == 'GET': # View return render_template('index.html', pads=KEY.pads, del_mode=True) else: # POST pad_id = request.form.getlist('pad_id')[0] KEY.del_pad(pad_id) return redirect('/delete')
POST # add pad to settings name = request.form.getlist('name')[0] keys = request.form.getlist('keys')[0].split() KEY.add_pad(name, *keys) return redirect('/') @app.route('/delete', methods=['GET', 'POST']) def delete():
63
64
80
15
48
kekeho/ctrlpad
ctrlpad.py
Python
delete
delete
36
46
36
37
bc39dbaeb563a6b006f41859ffaebe714a6e546d
bigcode/the-stack
train