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
858a6c0005ecf4572420cf4e
train
function
async def test_tickers(exchange, symbol): if exchange.has['fetchTickers']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) tickers = None try: # dump(green(exchange.id), 'fetching all tickers at once...') tickers = await exchange.fetch_ticker...
async def test_tickers(exchange, symbol):
if exchange.has['fetchTickers']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) tickers = None try: # dump(green(exchange.id), 'fetching all tickers at once...') tickers = await exchange.fetch_tickers() dump(green(exchange.id), '...
= await exchange.fetch_ohlcv(symbol) dump(green(exchange.id), 'fetched', green(len(ohlcvs)), 'OHLCVs') else: dump(yellow(exchange.id), 'fetching OHLCV not supported') # ------------------------------------------------------------------------------ async def test_tickers(exchange, symbol):
63
64
189
9
54
dnlsngr/ccxt
python/test/test_async.py
Python
test_tickers
test_tickers
149
165
149
149
18cd85b3bc25a6f32042995fc7c53db36a95ca74
bigcode/the-stack
train
aa451c27c92b9aef976051bb
train
class
class Argv(object): token_bucket = False verbose = False nonce = None exchange = None symbol = None pass
class Argv(object):
token_bucket = False verbose = False nonce = None exchange = None symbol = None pass
# ------------------------------------------------------------------------------ # logging.basicConfig(level=logging.INFO) # ------------------------------------------------------------------------------ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, root) # --------------------...
63
64
34
5
58
dnlsngr/ccxt
python/test/test_async.py
Python
Argv
Argv
27
33
27
27
2fee01f5fc58aeffc9637fbfcc05bfb4e174b679
bigcode/the-stack
train
b7018a59a5afeb91f6b85165
train
function
async def test_tickers_async(exchange): print('Activated here') dump(green(exchange.id), 'fetching all tickers by simultaneous multiple concurrent requests') symbols_to_load = get_active_symbols(exchange) input_coroutines = [exchange.fetchTicker(symbol) for symbol in symbols_to_load] tickers = await...
async def test_tickers_async(exchange):
print('Activated here') dump(green(exchange.id), 'fetching all tickers by simultaneous multiple concurrent requests') symbols_to_load = get_active_symbols(exchange) input_coroutines = [exchange.fetchTicker(symbol) for symbol in symbols_to_load] tickers = await asyncio.gather(*input_coroutines, retur...
for symbol in exchange.symbols if is_active_symbol(exchange, symbol)] def is_active_symbol(exchange, symbol): return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active'])) async def test_tickers_async(exchange):
63
64
155
8
55
dnlsngr/ccxt
python/test/test_async.py
Python
test_tickers_async
test_tickers_async
178
188
178
178
a2551208986b3209245d2815ac3e34a902b0b2f7
bigcode/the-stack
train
92fe3b1f4ad9357d5a88b294
train
function
def blue(s): return style(s, '\033[94m')
def blue(s):
return style(s, '\033[94m')
ccxt\npip3 uninstall ccxt\n\n') # ------------------------------------------------------------------------------ # string coloring functions def style(s, style): return str(s) # style + str (s) + '\033[0m' def green(s): return style(s, '\033[92m') def blue(s):
64
64
15
4
60
dnlsngr/ccxt
python/test/test_async.py
Python
blue
blue
67
68
67
67
6aabb2471bfdbce5ba1b1ff31f1ab44f1c12dcda
bigcode/the-stack
train
48ec57ea2583e17b4c1e5489
train
function
async def test_l2_order_books_async(exchange): dump(green(exchange.id), 'fetching all order books by simultaneous multiple concurrent requests') symbols_to_load = get_active_symbols(exchange) input_coroutines = [exchange.fetch_l2_order_book(symbol) for symbol in symbols_to_load] orderbooks = await async...
async def test_l2_order_books_async(exchange):
dump(green(exchange.id), 'fetching all order books by simultaneous multiple concurrent requests') symbols_to_load = get_active_symbols(exchange) input_coroutines = [exchange.fetch_l2_order_book(symbol) for symbol in symbols_to_load] orderbooks = await asyncio.gather(*input_coroutines, return_exceptions=...
): dump_error(red('[Error with symbol loading ticker]'), ' Symbol failed to load: {0}, ERROR: {1}'.format(symbol, ticker)) dump(green(exchange.id), 'fetched', green(len(list(tickers))), 'tickers') async def test_l2_order_books_async(exchange):
64
64
159
10
54
dnlsngr/ccxt
python/test/test_async.py
Python
test_l2_order_books_async
test_l2_order_books_async
191
200
191
191
fa9f5d5d888624fe779e5590804195c4a6040aa2
bigcode/the-stack
train
a2e101f2e42f69e10aabd051
train
function
def get_active_symbols(exchange): return [symbol for symbol in exchange.symbols if is_active_symbol(exchange, symbol)]
def get_active_symbols(exchange):
return [symbol for symbol in exchange.symbols if is_active_symbol(exchange, symbol)]
symbol]) dump(green(exchange.id), 'fetched', green(len(list(tickers.keys()))), 'tickers') elif argv.token_bucket: await test_tickers_async(exchange) if argv.token_bucket: await test_l2_order_books_async(exchange) # -------------------------------------------------------------------...
64
64
24
6
58
dnlsngr/ccxt
python/test/test_async.py
Python
get_active_symbols
get_active_symbols
170
171
170
170
481c160a9819a5c607591cd67a1630d71cbcb531
bigcode/the-stack
train
9e258ada26b7b83bd7b4c423
train
function
def style(s, style): return str(s) # style + str (s) + '\033[0m'
def style(s, style):
return str(s) # style + str (s) + '\033[0m'
!\nIt was previously installed into your site-packages folder by pip or pip3.\n\nTo ensure testing against the local folder uninstall it first by running the following commands:\npip uninstall ccxt\npip3 uninstall ccxt\n\n') # ------------------------------------------------------------------------------ # string colo...
64
64
26
6
57
dnlsngr/ccxt
python/test/test_async.py
Python
style
style
59
60
59
59
c4057c048bb1196845d423f5c365bbd5d2c7bb25
bigcode/the-stack
train
8fb3681e9696e26c76e94538
train
function
async def try_all_proxies(exchange, proxies=['']): current_proxy = 0 max_retries = len(proxies) # a special case for ccex if exchange.id == 'ccex' and max_retries > 1: current_proxy = 1 for num_retries in range(0, max_retries): try: exchange.proxy = proxies[current_proxy]...
async def try_all_proxies(exchange, proxies=['']):
current_proxy = 0 max_retries = len(proxies) # a special case for ccex if exchange.id == 'ccex' and max_retries > 1: current_proxy = 1 for num_retries in range(0, max_retries): try: exchange.proxy = proxies[current_proxy] dump(green(exchange.id), 'using proxy'...
) # time.sleep(delay) # marketSell = exchange.create_market_sell_order(symbol, amount) # print(marketSell) # time.sleep(delay) # limitBuy = exchange.create_limit_buy_order(symbol, amount, price) # print(limitBuy) # time.sleep(delay) # limitSell = exchange.create_limit_sell_order(symbo...
104
105
353
11
93
dnlsngr/ccxt
python/test/test_async.py
Python
try_all_proxies
try_all_proxies
338
367
338
338
ec123747d2667dde8c011bf0b98c3a3dd19a8c63
bigcode/the-stack
train
7f2a313f8bac39ef72fa35df
train
function
def yellow(s): return style(s, '\033[93m')
def yellow(s):
return style(s, '\033[93m')
string coloring functions def style(s, style): return str(s) # style + str (s) + '\033[0m' def green(s): return style(s, '\033[92m') def blue(s): return style(s, '\033[94m') def yellow(s):
64
64
15
4
60
dnlsngr/ccxt
python/test/test_async.py
Python
yellow
yellow
71
72
71
71
994d9dad7e69cfd690b49d72d7deb3a6705c2c9d
bigcode/the-stack
train
54396d7f08ae496d3b36d803
train
function
async def main(): if argv.exchange: if argv.exchange != 'theocean' and argv.exchange != 'theocean1': exchange = exchanges[argv.exchange] symbol = argv.symbol if hasattr(exchange, 'skip') and exchange.skip: dump(green(exchange.id), 'skipped') ...
async def main():
if argv.exchange: if argv.exchange != 'theocean' and argv.exchange != 'theocean1': exchange = exchanges[argv.exchange] symbol = argv.symbol if hasattr(exchange, 'skip') and exchange.skip: dump(green(exchange.id), 'skipped') else: ...
) exchange_config = {'verbose': argv.verbose} if sys.version_info[0] < 3: exchange_config.update({'enableRateLimit': True}) if id in config: exchange_config.update(config[id]) exchanges[id] = exchange(exchange_config) # -------------------------------------------------------------------...
63
64
155
4
59
dnlsngr/ccxt
python/test/test_async.py
Python
main
main
403
426
403
404
27942b6cfc667af5a4d5700c19610871591d4a62
bigcode/the-stack
train
7114dc6960abda796509051f
train
function
async def test_trades(exchange, symbol): if exchange.has['fetchTrades']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching trades...') trades = await exchange.fetch_trades(symbol) dump(green(exchange.id), gre...
async def test_trades(exchange, symbol):
if exchange.has['fetchTrades']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching trades...') trades = await exchange.fetch_trades(symbol) dump(green(exchange.id), green(symbol), 'fetched', green(len(list(tra...
(ticker['bid']), 'ask: ' + str(ticker['ask']), 'volume: ' + str(ticker['quoteVolume'])) else: dump(green(exchange.id), green(symbol), 'fetch_ticker() not supported') # ------------------------------------------------------------------------------ async def test_trades(exchange, symb...
63
64
106
9
54
dnlsngr/ccxt
python/test/test_async.py
Python
test_trades
test_trades
226
234
226
226
80df71ad229b709fe63938e30beb89d3d4193721
bigcode/the-stack
train
6170163b4c04ad906a1eb9fe
train
function
def dump(*args): print(' '.join([str(arg) for arg in args]))
def dump(*args):
print(' '.join([str(arg) for arg in args]))
(s, '\033[91m') def pink(s): return style(s, '\033[95m') def bold(s): return style(s, '\033[1m') def underline(s): return style(s, '\033[4m') # print a colored string def dump(*args):
64
64
19
5
58
dnlsngr/ccxt
python/test/test_async.py
Python
dump
dump
92
93
92
92
cf3c9e5cddb4e9e8ba1430f7e7c8fe8cbf309006
bigcode/the-stack
train
1c34562b604a36dafa4ea117
train
function
async def load_exchange(exchange): await exchange.load_markets()
async def load_exchange(exchange):
await exchange.load_markets()
response = await exchange.fetchGlobal() dump(green(response)) else: await test_order_book(exchange, symbol) await test_trades(exchange, symbol) await test_tickers(exchange, symbol) await test_ohlcv(exchange, symbol) # --------------------------------------------------------...
63
64
13
6
57
dnlsngr/ccxt
python/test/test_async.py
Python
load_exchange
load_exchange
256
257
256
256
f5063c29f44f05b9e9e2354e85d4219aea1116b3
bigcode/the-stack
train
b27d330a65dceb5a2e831423
train
function
async def test_exchange(exchange): dump(green('EXCHANGE: ' + exchange.id)) # delay = 2 keys = list(exchange.markets.keys()) # .......................................................................... # public API symbol = keys[0] symbols = [ 'BTC/USD', 'BTC/USDT', ...
async def test_exchange(exchange):
dump(green('EXCHANGE: ' + exchange.id)) # delay = 2 keys = list(exchange.markets.keys()) # .......................................................................... # public API symbol = keys[0] symbols = [ 'BTC/USD', 'BTC/USDT', 'BTC/CNY', 'BTC/EUR', ...
+ symbol)) await test_ticker(exchange, symbol) if exchange.id == 'coinmarketcap': response = await exchange.fetchGlobal() dump(green(response)) else: await test_order_book(exchange, symbol) await test_trades(exchange, symbol) await test_tickers(exchange, symbol) aw...
99
99
333
6
93
dnlsngr/ccxt
python/test/test_async.py
Python
test_exchange
test_exchange
260
310
260
261
f76e4b2bb28055b7a0a16952c673210f5651be43
bigcode/the-stack
train
427afe39381a67588da72585
train
function
def bold(s): return style(s, '\033[1m')
def bold(s):
return style(s, '\033[1m')
def blue(s): return style(s, '\033[94m') def yellow(s): return style(s, '\033[93m') def red(s): return style(s, '\033[91m') def pink(s): return style(s, '\033[95m') def bold(s):
64
64
15
4
60
dnlsngr/ccxt
python/test/test_async.py
Python
bold
bold
83
84
83
83
3dddc7e3726858834bb5cb5374cd188f55fcc437
bigcode/the-stack
train
0a7e6cae86fcbf23955ee2c6
train
function
def handle_all_unhandled_exceptions(type, value, traceback): dump_error(yellow(type), yellow(value), '\n\n' + yellow('\n'.join(format_tb(traceback)))) _exit(1) # unrecoverable crash
def handle_all_unhandled_exceptions(type, value, traceback):
dump_error(yellow(type), yellow(value), '\n\n' + yellow('\n'.join(format_tb(traceback)))) _exit(1) # unrecoverable crash
) for arg in args])) # print an error string def dump_error(*args): string = ' '.join([str(arg) for arg in args]) print(string) sys.stderr.write(string + "\n") # ------------------------------------------------------------------------------ def handle_all_unhandled_exceptions(type, value, traceback):
63
64
51
13
50
dnlsngr/ccxt
python/test/test_async.py
Python
handle_all_unhandled_exceptions
handle_all_unhandled_exceptions
106
108
106
106
8f0d8acafffc55482b93753f9ec287bdd1977159
bigcode/the-stack
train
c7ce83c3a941dc1baf8fa305
train
function
async def test_symbol(exchange, symbol): dump(green('SYMBOL: ' + symbol)) await test_ticker(exchange, symbol) if exchange.id == 'coinmarketcap': response = await exchange.fetchGlobal() dump(green(response)) else: await test_order_book(exchange, symbol) await test_trades(...
async def test_symbol(exchange, symbol):
dump(green('SYMBOL: ' + symbol)) await test_ticker(exchange, symbol) if exchange.id == 'coinmarketcap': response = await exchange.fetchGlobal() dump(green(response)) else: await test_order_book(exchange, symbol) await test_trades(exchange, symbol) await test_tickers...
await exchange.fetch_trades(symbol) dump(green(exchange.id), green(symbol), 'fetched', green(len(list(trades))), 'trades') else: dump(green(exchange.id), green(symbol), 'fetch_trades() not supported') # ------------------------------------------------------------------------------ async def test_s...
63
64
93
8
55
dnlsngr/ccxt
python/test/test_async.py
Python
test_symbol
test_symbol
239
251
239
239
ed0b33ddb78d7c03efb0f74f8f17c13757368fe4
bigcode/the-stack
train
8a0bca1e3539f5be1805103b
train
function
async def test_order_book(exchange, symbol): if exchange.has['fetchOrderBook']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching order book...') orderbook = await exchange.fetch_order_book(symbol) dump( ...
async def test_order_book(exchange, symbol):
if exchange.has['fetchOrderBook']: delay = int(exchange.rateLimit / 1000) await asyncio.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching order book...') orderbook = await exchange.fetch_order_book(symbol) dump( green(exchange.id), green...
traceback): dump_error(yellow(type), yellow(value), '\n\n' + yellow('\n'.join(format_tb(traceback)))) _exit(1) # unrecoverable crash sys.excepthook = handle_all_unhandled_exceptions # ------------------------------------------------------------------------------ async def test_order_book(exchange, symbol):...
65
66
222
9
56
dnlsngr/ccxt
python/test/test_async.py
Python
test_order_book
test_order_book
116
132
116
116
e9003ef5f151106bc1ec6ca5a9b323729e96128d
bigcode/the-stack
train
f56d2afc9031dc685d93ee6b
train
function
@ti.func def inside_left(p, c, r): return inside(p, c, r) and p[0] < c[0]
@ti.func def inside_left(p, c, r):
return inside(p, c, r) and p[0] < c[0]
box_max, (1 - lo) * o1 + lo * o2) < radius * radius @ti.func def inside(p, c, r): return (p - c).norm_sqr() <= r * r @ti.func def inside_left(p, c, r):
64
64
32
13
50
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
inside_left
inside_left
167
169
167
168
a07e8f4bdefb4f450774b44fe2b3f8e1259a16c7
bigcode/the-stack
train
d1d2e593a26c585b10c8210f
train
function
@ti.func def point_aabb_distance2(box_min, box_max, o): p = ti.Vector([0.0, 0.0, 0.0]) for i in ti.static(range(3)): p[i] = ti.max(ti.min(o[i], box_max[i]), box_min[i]) return (p - o).norm_sqr()
@ti.func def point_aabb_distance2(box_min, box_max, o):
p = ti.Vector([0.0, 0.0, 0.0]) for i in ti.static(range(3)): p[i] = ti.max(ti.min(o[i], box_max[i]), box_min[i]) return (p - o).norm_sqr()
= d.dot(norm) if abs(denom) > eps: dist = norm.dot(pt_on_plane - pos) / denom hit_pos = pos + d * dist return dist, hit_pos @ti.func def point_aabb_distance2(box_min, box_max, o):
64
64
80
18
45
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
point_aabb_distance2
point_aabb_distance2
131
136
131
132
92ccd830ea29c52fb2d3636d7e641c72e4571a74
bigcode/the-stack
train
24e5f180a9822805c5c10504
train
function
@ti.func def ray_aabb_intersection(box_min, box_max, o, d): intersect = 1 near_int = -inf far_int = inf for i in ti.static(range(3)): if d[i] == 0: if o[i] < box_min[i] or o[i] > box_max[i]: intersect = 0 else: i1 = (box_min[i] - o[i]) / d[i] ...
@ti.func def ray_aabb_intersection(box_min, box_max, o, d):
intersect = 1 near_int = -inf far_int = inf for i in ti.static(range(3)): if d[i] == 0: if o[i] < box_min[i] or o[i] > box_max[i]: intersect = 0 else: i1 = (box_min[i] - o[i]) / d[i] i2 = (box_max[i] - o[i]) / d[i] new_fa...
rd = (ni_over_nt * (d - n * dt) - n * ti.sqrt(discr)).normalized() else: rd *= 0.0 return has_r, rd @ti.func def ray_aabb_intersection(box_min, box_max, o, d):
64
64
198
20
43
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
ray_aabb_intersection
ray_aabb_intersection
42
65
42
43
870cb22d2d23f89b07d4b93279a6dc9bc79b80cb
bigcode/the-stack
train
13666f56f19865ab25f7a391
train
function
@ti.func def inside(p, c, r): return (p - c).norm_sqr() <= r * r
@ti.func def inside(p, c, r):
return (p - c).norm_sqr() <= r * r
> d1: hi = m2 else: lo = m1 return point_aabb_distance2(box_min, box_max, (1 - lo) * o1 + lo * o2) < radius * radius @ti.func def inside(p, c, r):
64
64
28
12
51
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
inside
inside
162
164
162
163
83ff29a6f666c5f41cec7be142975bef4defd10e
bigcode/the-stack
train
3d3dcd8c923bccb412d0f4b4
train
function
@ti.func def sphere_aabb_intersect_motion(box_min, box_max, o1, o2, radius): lo = 0.0 hi = 1.0 while lo + 1e-5 < hi: m1 = 2 * lo / 3 + hi / 3 m2 = lo / 3 + 2 * hi / 3 d1 = point_aabb_distance2(box_min, box_max, (1 - m1) * o1 + m1 * o2) d2 = point_aabb_distance2(box_min, box_m...
@ti.func def sphere_aabb_intersect_motion(box_min, box_max, o1, o2, radius):
lo = 0.0 hi = 1.0 while lo + 1e-5 < hi: m1 = 2 * lo / 3 + hi / 3 m2 = lo / 3 + 2 * hi / 3 d1 = point_aabb_distance2(box_min, box_max, (1 - m1) * o1 + m1 * o2) d2 = point_aabb_distance2(box_min, box_max, (1 - m2) * o1 + m2 * o2) if d2 > d1: hi = m2 ...
ti.func def sphere_aabb_intersect(box_min, box_max, o, radius): return point_aabb_distance2(box_min, box_max, o) < radius * radius @ti.func def sphere_aabb_intersect_motion(box_min, box_max, o1, o2, radius):
64
64
205
25
38
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
sphere_aabb_intersect_motion
sphere_aabb_intersect_motion
144
159
144
145
29f53873679e34923e826bbd2394ba7e692b7d0b
bigcode/the-stack
train
c2daee7c227dea76e9e4a0ab
train
function
@ti.func def sphere_aabb_intersect(box_min, box_max, o, radius): return point_aabb_distance2(box_min, box_max, o) < radius * radius
@ti.func def sphere_aabb_intersect(box_min, box_max, o, radius):
return point_aabb_distance2(box_min, box_max, o) < radius * radius
0]) for i in ti.static(range(3)): p[i] = ti.max(ti.min(o[i], box_max[i]), box_min[i]) return (p - o).norm_sqr() @ti.func def sphere_aabb_intersect(box_min, box_max, o, radius):
64
64
40
20
44
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
sphere_aabb_intersect
sphere_aabb_intersect
139
141
139
140
a2ca99e8b3b9009f337c56e8eb9a270593db2304
bigcode/the-stack
train
625a92f1b39165befca0ddd2
train
function
def Vector2(x, y): return ti.Vector([x, y])
def Vector2(x, y):
return ti.Vector([x, y])
(p, c, r): return inside(p, c, r) and p[0] < c[0] @ti.func def inside_right(p, c, r): return inside(p, c, r) and p[0] > c[0] def Vector2(x, y):
64
64
16
7
57
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
Vector2
Vector2
177
178
177
177
dfe4938102ba02155fc68cce22cb4c2870403feb
bigcode/the-stack
train
2332c02965221566b0575ba5
train
function
@ti.func def reflect(d, n): # Assuming |d| and |n| are normalized return d - 2.0 * d.dot(n) * n
@ti.func def reflect(d, n): # Assuming |d| and |n| are normalized
return d - 2.0 * d.dot(n) * n
ay = ti.sqrt(r) ax = ti.sqrt(1 - r) return ax * (ti.cos(phi) * u + ti.sin(phi) * v) + ay * n @ti.func def reflect(d, n): # Assuming |d| and |n| are normalized
64
64
39
23
40
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
reflect
reflect
22
25
22
24
9bb603a68a634c0f6917a4a95a25e3e7fc04c397
bigcode/the-stack
train
331da983a95755be5fd736be
train
function
@ti.func def intersect_sphere(pos, d, center, radius): T = pos - center A = 1.0 B = 2.0 * T.dot(d) C = T.dot(T) - radius * radius delta = B * B - 4.0 * A * C dist = inf hit_pos = ti.Vector([0.0, 0.0, 0.0]) if delta > -1e-4: delta = ti.max(delta, 0) sdelta = ti.sqrt(delta...
@ti.func def intersect_sphere(pos, d, center, radius):
T = pos - center A = 1.0 B = 2.0 * T.dot(d) C = T.dot(T) - radius * radius delta = B * B - 4.0 * A * C dist = inf hit_pos = ti.Vector([0.0, 0.0, 0.0]) if delta > -1e-4: delta = ti.max(delta, 0) sdelta = ti.sqrt(delta) ratio = 0.5 / A ret1 = ratio * (-B - ...
near_int = ti.max(new_near_int, near_int) if near_int > far_int: intersect = 0 return intersect, near_int, far_int # (T + x d)(T + x d) = r * r # T*T + 2Td x + x^2 = r * r # x^2 + 2Td x + (T * T - r * r) = 0 refine = True @ti.func def intersect_sphere(pos, d, center, radius):
116
116
388
16
99
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
intersect_sphere
intersect_sphere
75
117
75
76
04df9e2e23ae18f0b8dc7e5f897a8dc485672372
bigcode/the-stack
train
a9713f7b9d4375e7872794b9
train
function
@ti.func def ray_plane_intersect(pos, d, pt_on_plane, norm): dist = inf hit_pos = ti.Vector([0.0, 0.0, 0.0]) denom = d.dot(norm) if abs(denom) > eps: dist = norm.dot(pt_on_plane - pos) / denom hit_pos = pos + d * dist return dist, hit_pos
@ti.func def ray_plane_intersect(pos, d, pt_on_plane, norm):
dist = inf hit_pos = ti.Vector([0.0, 0.0, 0.0]) denom = d.dot(norm) if abs(denom) > eps: dist = norm.dot(pt_on_plane - pos) / denom hit_pos = pos + d * dist return dist, hit_pos
0: # dist = ret2 # hit_pos = new_pos + ratio * (-B + sdelta) * d else: dist = inf return dist, hit_pos @ti.func def ray_plane_intersect(pos, d, pt_on_plane, norm):
64
64
93
19
44
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
ray_plane_intersect
ray_plane_intersect
120
128
120
121
873362c4d3cec44d6e89ddb2509c6b1bf8c9ad8e
bigcode/the-stack
train
643d962c263ef28b42c59030
train
function
@ti.func def inside_right(p, c, r): return inside(p, c, r) and p[0] > c[0]
@ti.func def inside_right(p, c, r):
return inside(p, c, r) and p[0] > c[0]
, r): return (p - c).norm_sqr() <= r * r @ti.func def inside_left(p, c, r): return inside(p, c, r) and p[0] < c[0] @ti.func def inside_right(p, c, r):
64
64
32
13
51
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
inside_right
inside_right
172
174
172
173
6a67c36dfe6610d7d8900a7854a1c6e0f8ebc2e6
bigcode/the-stack
train
73f2f9c5a8d4ba1d798bee77
train
function
@ti.func def out_dir(n): u = ti.Vector([1.0, 0.0, 0.0]) if ti.abs(n[1]) < 1 - 1e-3: u = n.cross(ti.Vector([0.0, 1.0, 0.0])).normalized() v = n.cross(u) phi = 2 * math.pi * ti.random(ti.f32) r = ti.random(ti.f32) ay = ti.sqrt(r) ax = ti.sqrt(1 - r) return ax * (ti.cos(phi) * u + t...
@ti.func def out_dir(n):
u = ti.Vector([1.0, 0.0, 0.0]) if ti.abs(n[1]) < 1 - 1e-3: u = n.cross(ti.Vector([0.0, 1.0, 0.0])).normalized() v = n.cross(u) phi = 2 * math.pi * ti.random(ti.f32) r = ti.random(ti.f32) ay = ti.sqrt(r) ax = ti.sqrt(1 - r) return ax * (ti.cos(phi) * u + ti.sin(phi) * v) + ay * n
import math import taichi as ti eps = 1e-4 inf = 1e10 @ti.func def out_dir(n):
33
64
146
9
23
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
out_dir
out_dir
9
19
9
10
a3a7fdd39149e5ab197f7cd489868bff79a14976
bigcode/the-stack
train
d96d56a75d269543007c7b1a
train
function
@ti.func def refract(d, n, ni_over_nt): # Assuming |d| and |n| are normalized has_r, rd = 0, d dt = d.dot(n) discr = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt) if discr > 0.0: has_r = 1 rd = (ni_over_nt * (d - n * dt) - n * ti.sqrt(discr)).normalized() else: rd *= 0....
@ti.func def refract(d, n, ni_over_nt): # Assuming |d| and |n| are normalized
has_r, rd = 0, d dt = d.dot(n) discr = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt) if discr > 0.0: has_r = 1 rd = (ni_over_nt * (d - n * dt) - n * ti.sqrt(discr)).normalized() else: rd *= 0.0 return has_r, rd
def reflect(d, n): # Assuming |d| and |n| are normalized return d - 2.0 * d.dot(n) * n @ti.func def refract(d, n, ni_over_nt): # Assuming |d| and |n| are normalized
64
64
130
28
35
Jack12xl/taichi
examples/rendering/renderer_utils.py
Python
refract
refract
28
39
28
30
cb1cd41ea40eeaca80e0f8cf9458cdb07bc90c83
bigcode/the-stack
train
7c36038b82a93862317877ec
train
function
@mark.asyncio async def test_key_store(store: Store): # test key operations in a new session async with store as session: # Create a new keypair keypair = Key.generate(KeyAlg.ED25519) # Store keypair key_name = "testkey" await session.insert_key( key_name, ke...
@mark.asyncio async def test_key_store(store: Store): # test key operations in a new session
async with store as session: # Create a new keypair keypair = Key.generate(KeyAlg.ED25519) # Store keypair key_name = "testkey" await session.insert_key( key_name, keypair, metadata="metadata", tags={"a": "b"} ) # Fetch keypair fetch_key ...
": "b"} ) assert len(found) == 1 and dict(found[0]) == TEST_ENTRY await txn.commit() # Check the transaction was committed async with store.session() as session: found = await session.fetch(TEST_ENTRY["category"], TEST_ENTRY["name"]) assert dict(found) == TEST_ENTRY @ma...
95
95
317
24
70
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_key_store
test_key_store
141
177
141
143
9bc2c5ad3d15435cb22952ac5e524fc7278f67ae
bigcode/the-stack
train
d2f6cc486d5280e2e82af672
train
function
@mark.asyncio async def test_profile(store: Store): profile = await store.create_profile() await store.remove_profile(profile)
@mark.asyncio async def test_profile(store: Store):
profile = await store.create_profile() await store.remove_profile(profile)
"c"}, limit=1 ) assert len(keys) == 1 and keys[0].name == key_name # Remove await session.remove_key(key_name) assert await session.fetch_key(key_name) is None @mark.asyncio async def test_profile(store: Store):
64
64
28
13
50
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_profile
test_profile
180
183
180
181
e2c65f62a096ab80cf6c70b05441c88397fbaede
bigcode/the-stack
train
fb6d3dcab2327cde34993769
train
function
@mark.asyncio async def test_remove_all(store: Store): async with store as session: # Insert a new entry await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Remove using remov...
@mark.asyncio async def test_remove_all(store: Store):
async with store as session: # Insert a new entry await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Remove using remove_all await session.remove_all( TEST...
dict(found[0]) == TEST_ENTRY # Remove entry await session.remove(TEST_ENTRY["category"], TEST_ENTRY["name"]) found = await session.fetch(TEST_ENTRY["category"], TEST_ENTRY["name"]) assert found is None @mark.asyncio async def test_remove_all(store: Store):
64
64
147
14
49
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_remove_all
test_remove_all
64
85
64
66
8eb3fdbf91e7a4fb6ce78754b02112a7f6507940
bigcode/the-stack
train
4494c8921c188ce66ed86b01
train
function
@mark.asyncio async def test_scan(store: Store): async with store as session: await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Scan entries by category and (optional) tag filter) r...
@mark.asyncio async def test_scan(store: Store):
async with store as session: await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Scan entries by category and (optional) tag filter) rows = await store.scan( TEST_ENTRY["catego...
a", "$and": [{"enctag": "b"}, {"enctag": "c"}]}, ), # Check removed found = await session.fetch(TEST_ENTRY["category"], TEST_ENTRY["name"]) assert found is None @mark.asyncio async def test_scan(store: Store):
64
64
117
13
50
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_scan
test_scan
88
103
88
90
11c733287ca2ac515fdeeac14606075aeb9af526
bigcode/the-stack
train
0c118859c044d942101ae504
train
function
@mark.asyncio async def test_insert_update(store: Store): async with store as session: # Insert a new entry await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Count rows by c...
@mark.asyncio async def test_insert_update(store: Store):
async with store as session: # Insert a new entry await session.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Count rows by category and (optional) tag filter assert ( ...
async def store() -> Store: key = Store.generate_raw_key(b"00000000000000000000000000000My1") store = await Store.provision(TEST_STORE_URI, "raw", key, recreate=True) yield store await store.close(remove=True) @mark.asyncio async def test_insert_update(store: Store):
74
74
248
14
60
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_insert_update
test_insert_update
29
61
29
31
0935873cb5f1ddff84a1d9e01ec7e4787c0439ac
bigcode/the-stack
train
1b3772aa25ad25a3a4185b6d
train
function
@fixture async def store() -> Store: key = Store.generate_raw_key(b"00000000000000000000000000000My1") store = await Store.provision(TEST_STORE_URI, "raw", key, recreate=True) yield store await store.close(remove=True)
@fixture async def store() -> Store:
key = Store.generate_raw_key(b"00000000000000000000000000000My1") store = await Store.provision(TEST_STORE_URI, "raw", key, recreate=True) yield store await store.close(remove=True)
TEST_ENTRY = { "category": "test category", "name": "test name", "value": b"test_value", "tags": {"~plaintag": "a", "enctag": {"b", "c"}}, } @fixture async def store() -> Store:
64
64
62
10
54
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
store
store
21
26
21
22
c7a841a656c81386485932153e53267ffb3540c1
bigcode/the-stack
train
d49228666e956f4e94ee2d91
train
function
@mark.asyncio async def test_transaction(store: Store): async with store.transaction() as txn: # Insert a new entry await txn.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Count rows ...
@mark.asyncio async def test_transaction(store: Store):
async with store.transaction() as txn: # Insert a new entry await txn.insert( TEST_ENTRY["category"], TEST_ENTRY["name"], TEST_ENTRY["value"], TEST_ENTRY["tags"], ) # Count rows by category and (optional) tag filter assert ( ...
by category and (optional) tag filter) rows = await store.scan( TEST_ENTRY["category"], {"~plaintag": "a", "enctag": "b"} ).fetch_all() assert len(rows) == 1 and dict(rows[0]) == TEST_ENTRY @mark.asyncio async def test_transaction(store: Store):
75
75
251
13
61
svitzebec/aries-askar
wrappers/python/tests/test_store.py
Python
test_transaction
test_transaction
106
138
106
107
09226fd36eee438cbb6a7d61917090fd80aa9c48
bigcode/the-stack
train
a5ef61b6b518435820f029e2
train
class
class Bar(Foo): def __init__(self, name, *args, **kwargs): super(Bar, self).__init__(name, args, kwargs) f = Far(name, args, kwargs)
class Bar(Foo):
def __init__(self, name, *args, **kwargs): super(Bar, self).__init__(name, args, kwargs) f = Far(name, args, kwargs)
License : BSD # # Copyright (c) 2020 DecisionScients # # =========================================================================== # #%% from abc import ABC class Foo(ABC): def __init__(self, name, *args, **kwa...
64
64
46
5
59
john-james-sf/DataStudio
datastudio/core/lab.py
Python
Bar
Bar
27
30
27
27
0128f5570928026d6843446e7c5f8cf2ea88db7b
bigcode/the-stack
train
1422d5d795688b72e0d89cea
train
class
class Far: def __init__(self, name, *args, **kwargs): print(name, *args, **kwargs)
class Far:
def __init__(self, name, *args, **kwargs): print(name, *args, **kwargs)
args, **kwargs): print(name, *args, **kwargs) class Bar(Foo): def __init__(self, name, *args, **kwargs): super(Bar, self).__init__(name, args, kwargs) f = Far(name, args, kwargs) class Far:
63
64
28
3
60
john-james-sf/DataStudio
datastudio/core/lab.py
Python
Far
Far
32
34
32
32
eef421188913ffb08e2b497371c97db63f4a09d2
bigcode/the-stack
train
2b1ce2ad8368e9793408d56a
train
class
class Boo: def __init__(self, name, path): print(name, path)
class Boo:
def __init__(self, name, path): print(name, path)
, *args, **kwargs): super(Bar, self).__init__(name, args, kwargs) f = Far(name, args, kwargs) class Far: def __init__(self, name, *args, **kwargs): print(name, *args, **kwargs) class Boo:
64
64
20
3
61
john-james-sf/DataStudio
datastudio/core/lab.py
Python
Boo
Boo
36
38
36
36
f999600771f79d2cee1af074fefb48112242eb12
bigcode/the-stack
train
5cb389936030b6f106899c5a
train
class
class Foo(ABC): def __init__(self, name, *args, **kwargs): print(name, *args, **kwargs)
class Foo(ABC):
def __init__(self, name, *args, **kwargs): print(name, *args, **kwargs)
49:16 am # # Modified By : John James (jjames@decisionscients.com>) # # --------------------------------------------------------------------------- # # License : BSD # # Copyright (c) 2020 DecisionScients ...
64
64
30
5
58
john-james-sf/DataStudio
datastudio/core/lab.py
Python
Foo
Foo
23
25
23
23
b4aad9f186a443de72bb6b78b457251225cf6a06
bigcode/the-stack
train
73ad6bf9de576b06a354c2e7
train
function
def createMafDatabase(syn, databaseToSynIdMappingDf,testing=False,staging=False): mafDatabaseSynId = process_functions.getDatabaseSynId(syn, "vcf2maf", databaseToSynIdMappingDf=databaseToSynIdMappingDf) mafDatabaseEnt = syn.get(mafDatabaseSynId) mafCols = list(syn.getTableColumns(mafDatabaseSynId)) sche...
def createMafDatabase(syn, databaseToSynIdMappingDf,testing=False,staging=False):
mafDatabaseSynId = process_functions.getDatabaseSynId(syn, "vcf2maf", databaseToSynIdMappingDf=databaseToSynIdMappingDf) mafDatabaseEnt = syn.get(mafDatabaseSynId) mafCols = list(syn.getTableColumns(mafDatabaseSynId)) schema = synapseclient.Schema(name='Narrow MAF %s Database' % time.time(), columns=maf...
reeLink=oncotreeLink, fileSynId=fileSynId, validVCF=validVCF, path_to_GENIE=path_to_GENIE, vcf2mafPath=vcf2mafPath, veppath=veppath,vepdata=vepdata, processing=processing,data...
126
126
421
22
103
kdaily/Genie
genie/input_to_database.py
Python
createMafDatabase
createMafDatabase
184
206
184
184
e489f3985fe0c92cc2eabd0f836971a87bb7b852
bigcode/the-stack
train
018820e593f294238c1efb80
train
function
def input_to_database(syn, center, process, testing, only_validate, vcf2maf_path, vep_path, vep_data, database_to_synid_mappingdf, center_mapping_df, reference=None, delete_old=False, oncotree_link=None, thread=1): if only_validate: log_path = os.path.join(process_functions.SCRIPT_DIR, "%s_validation_log.tx...
def input_to_database(syn, center, process, testing, only_validate, vcf2maf_path, vep_path, vep_data, database_to_synid_mappingdf, center_mapping_df, reference=None, delete_old=False, oncotree_link=None, thread=1):
if only_validate: log_path = os.path.join(process_functions.SCRIPT_DIR, "%s_validation_log.txt" % center) else: log_path = os.path.join(process_functions.SCRIPT_DIR, "%s_%s_log.txt" % (center, process)) logFormatter = logging.Formatter("%(asctime)s [%(name)s][%(levelname)s] %(message)s") ...
IdMappingDf), ["id"], to_delete=True) paths = inputValidStatus['path'] filenames = [os.path.basename(name) for name in paths] del inputValidStatus['path'] logger.info("UPDATE VALIDATION STATUS DATABASE") inputValidStatus['center'] = center #Remove fixed duplicated files ...
256
256
1,076
58
198
kdaily/Genie
genie/input_to_database.py
Python
input_to_database
input_to_database
300
381
300
300
9051ddd147de83a81c23bcc11a9d1f12e7f1a4e7
bigcode/the-stack
train
599e65e1cb2b6cde141396cc
train
function
def getFileType(syn, paths, name, center): fileType = None for fileNameFormat in PROCESS_FILES: try: fileType = PROCESS_FILES[fileNameFormat](syn, center).validateFilename(paths) except AssertionError as e: continue if fileType is not None: break r...
def getFileType(syn, paths, name, center):
fileType = None for fileNameFormat in PROCESS_FILES: try: fileType = PROCESS_FILES[fileNameFormat](syn, center).validateFilename(paths) except AssertionError as e: continue if fileType is not None: break return(fileType)
": allFiles.append(([synid],[reNameFile(syn, synid)])) elif not name.endswith(".vcf"): allFiles.append(([synid],[reNameFile(syn, synid)])) return(allFiles) def getFileType(syn, paths, name, center):
64
64
75
13
51
kdaily/Genie
genie/input_to_database.py
Python
getFileType
getFileType
64
73
64
64
ffb58b9e4b5bd746f80743015d24894b17689a75
bigcode/the-stack
train
6214680444e28df90051581d
train
function
def validation(syn, center, process, center_mapping_df, databaseToSynIdMappingDf, thread, testing, oncotreeLink): centerInputSynId = center_mapping_df['inputSynId'][center_mapping_df['center'] == center][0] logger.info("Center: " + center) allFiles = getCenterInputFiles(syn, centerInputSynId, center, proces...
def validation(syn, center, process, center_mapping_df, databaseToSynIdMappingDf, thread, testing, oncotreeLink):
centerInputSynId = center_mapping_df['inputSynId'][center_mapping_df['center'] == center][0] logger.info("Center: " + center) allFiles = getCenterInputFiles(syn, centerInputSynId, center, process) allFiles = pd.DataFrame(allFiles,columns=['synId','filePaths']) #If a center has no files, then return...
DatabaseSynId(syn, "dbMapping", test=testing),databaseToSynIdMappingDf)) if not staging and not testing: #Make sure to store the newly created maf db synid into the staging synapse mapping databaseToSynIdMapping = syn.tableQuery("SELECT * FROM syn12094210 where Database = 'vcf2maf'") databas...
256
256
1,492
29
226
kdaily/Genie
genie/input_to_database.py
Python
validation
validation
209
298
209
209
c9f2942384f90eaf7650f094db4473b7330b2221
bigcode/the-stack
train
6710de6572fa56b6aae52cf8
train
function
def reNameFile(syn, synId): temp = syn.get(synId) dirname = os.path.dirname(temp.path) newPath = os.path.join(dirname, temp.name) if newPath != temp.path: shutil.copyfile(temp.path, newPath) return(newPath)
def reNameFile(syn, synId):
temp = syn.get(synId) dirname = os.path.dirname(temp.path) newPath = os.path.join(dirname, temp.name) if newPath != temp.path: shutil.copyfile(temp.path, newPath) return(newPath)
import os from multiprocessing import Pool import pandas as pd import subprocess import datetime import subprocess import shutil import time import toRetract import write_invalid_reasons #Configuration file from genie import PROCESS_FILES, process_functions, validate def reNameFile(syn, synId):
64
64
63
10
53
kdaily/Genie
genie/input_to_database.py
Python
reNameFile
reNameFile
25
31
25
25
16b4c4f2c1f8e7e7a974cbc4df5412d054a0db05
bigcode/the-stack
train
24ab4757a64420d296269ca3
train
function
def processFiles(syn, validFiles, center, path_to_GENIE, threads, center_mapping_df, oncotreeLink, databaseToSynIdMappingDf, validVCF=None, vcf2mafPath=None, veppath=None, vepdata=None, processing="main", test=False, reference=None): logger.info...
def processFiles(syn, validFiles, center, path_to_GENIE, threads, center_mapping_df, oncotreeLink, databaseToSynIdMappingDf, validVCF=None, vcf2mafPath=None, veppath=None, vepdata=None, processing="main", test=False, reference=None):
logger.info("PROCESSING %s FILES: %d" % (center, len(validFiles))) centerStagingFolder = os.path.join(path_to_GENIE, center) centerStagingSynId = center_mapping_df['stagingSynId'][center_mapping_df['center'] == center][0] #PROCESS_FILES is in config_process_scripts.py if not os.path.exists(centerSta...
synId, message, name] for synId, name in zip(x['synId'],names)]) else: return([[synId,path,md5,status,name,modifiedOn,fileType] for synId, path, md5, status, name, modifiedOn in zip(x['synId'],paths, md5s, statuses, names, modifiedOns)], [[synId, errorMes, name] for synId, errorMes, name in zip(x['synId'],e...
189
189
631
72
116
kdaily/Genie
genie/input_to_database.py
Python
processFiles
processFiles
138
181
138
143
6c7834d79d90bd0eeceea64ec718317803523e65
bigcode/the-stack
train
56f2d258ccc977e2f44d5fc0
train
function
def validateFile(syn, validationStatusDf, errorTracker, center, threads, x, testing, oncotreeLink): names = [os.path.basename(i) for i in x['filePaths']] logger.info("VALIDATING %s" % ", ".join(names)) paths = x['filePaths'] name = names[0] entities = [syn.get(synId,downloadFile=False) for synId in...
def validateFile(syn, validationStatusDf, errorTracker, center, threads, x, testing, oncotreeLink):
names = [os.path.basename(i) for i in x['filePaths']] logger.info("VALIDATING %s" % ", ".join(names)) paths = x['filePaths'] name = names[0] entities = [syn.get(synId,downloadFile=False) for synId in x['synId']] md5s = [entity.md5 for entity in entities] modifiedOns = [synapseclient.utils.t...
in filenames: logger.info(name) paired=False if name in CLINICAL_PAIR_NAME: paired = True clinicalpair.append(synid) if len(clinicalpair) == 2: syns = [i for i in clinicalpair] paths = [reNameFile(syn, i) fo...
256
256
873
26
230
kdaily/Genie
genie/input_to_database.py
Python
validateFile
validateFile
75
132
75
75
e96408a13b4dd3235a5168e7334dab66ddd2c164
bigcode/the-stack
train
046ec2fd6bcf6585fdfeffb9
train
function
def main(): """Set up argument parser and returns""" parser = argparse.ArgumentParser( description='GENIE center inputs to database') parser.add_argument("process",choices=['vcf','maf','main','mafSP'], help='Process vcf, maf or the rest of the files') parser.add_argument(...
def main():
"""Set up argument parser and returns""" parser = argparse.ArgumentParser( description='GENIE center inputs to database') parser.add_argument("process",choices=['vcf','maf','main','mafSP'], help='Process vcf, maf or the rest of the files') parser.add_argument('--center', ...
, test=testing, processing=process,reference=reference) #Should add in this process end tracking before the deletion of samples processTracker = syn.tableQuery("SELECT timeEndProcessing FROM %s where center = '%s' and processingType = '%s'" % (processTrackerSynId, center, process))...
256
256
1,255
3
253
kdaily/Genie
genie/input_to_database.py
Python
main
main
384
465
384
384
8d426ee4013907e866dab40d484dc4c9d5798f01
bigcode/the-stack
train
dbe8e6ad562692a771ed6ad9
train
function
def getCenterInputFiles(syn, synId, center, process="main"): """ This function walks through each center's input directory and validates every file """ ################################################################ ##If a file has not changed than it does not need to be processed!!!! #########...
def getCenterInputFiles(syn, synId, center, process="main"):
""" This function walks through each center's input directory and validates every file """ ################################################################ ##If a file has not changed than it does not need to be processed!!!! ################################################################ l...
from genie import PROCESS_FILES, process_functions, validate def reNameFile(syn, synId): temp = syn.get(synId) dirname = os.path.dirname(temp.path) newPath = os.path.join(dirname, temp.name) if newPath != temp.path: shutil.copyfile(temp.path, newPath) return(newPath) def getCenterInputFile...
91
91
306
17
74
kdaily/Genie
genie/input_to_database.py
Python
getCenterInputFiles
getCenterInputFiles
33
62
33
33
0193bc9330a9769af6d9910417f6db5a717988ca
bigcode/the-stack
train
b775e35ca1a5f6a377c71490
train
function
def run(model, criterion, optimizer, dataset, is_training: bool, metrics): model.train(is_training) dictionary = collections.defaultdict(int) counter = 0 with torch.set_grad_enabled(is_training): for X, y in dataset: counter += 1 y_pred = model(X.squeeze().reshape(X.sha...
def run(model, criterion, optimizer, dataset, is_training: bool, metrics):
model.train(is_training) dictionary = collections.defaultdict(int) counter = 0 with torch.set_grad_enabled(is_training): for X, y in dataset: counter += 1 y_pred = model(X.squeeze().reshape(X.shape[0], -1)) loss = criterion(y_pred, y) for name, ...
import collections import metrics import torch # Train # Validate # On given arguments, data def run(model, criterion, optimizer, dataset, is_training: bool, metrics):
39
64
140
17
21
szymonmaszke/AiCorExample
src/runner.py
Python
run
run
10
30
10
10
dd9fb0dbed7b435a2537ac2aa7d2b8cf5d7965ad
bigcode/the-stack
train
43889c5a81e70a62a9fa74df
train
class
class TaggableManager(BaseTaggableManager): def formfield(self, form_class=TagField, **kwargs): defaults = { "label": capfirst(self.verbose_name), "help_text": None, "required": not self.blank, "widget": TagSelectize, } defaults.update(kwargs) ...
class TaggableManager(BaseTaggableManager):
def formfield(self, form_class=TagField, **kwargs): defaults = { "label": capfirst(self.verbose_name), "help_text": None, "required": not self.blank, "widget": TagSelectize, } defaults.update(kwargs) return form_class(**defaults)
from django.utils.text import capfirst from taggit.forms import TagField from taggit.managers import TaggableManager as BaseTaggableManager from .widgets import TagSelectize class TaggableManager(BaseTaggableManager):
48
64
75
9
38
yswtrue/taggit-selectize
taggit_selectize/managers.py
Python
TaggableManager
TaggableManager
7
16
7
7
518567240e72dc1710724868d2e780e7a6ce0ba8
bigcode/the-stack
train
9a4e30487feb903b85f3970e
train
class
class TeamManipulator(ManipulatorBase[Team]): """ Handle Team database writes. """ """ @classmethod def getCacheKeysAndControllers(cls, affected_refs): return CacheClearer.get_team_cache_keys_and_controllers(affected_refs) @classmethod def postDeleteHook(cls, teams): # ...
class TeamManipulator(ManipulatorBase[Team]):
""" Handle Team database writes. """ """ @classmethod def getCacheKeysAndControllers(cls, affected_refs): return CacheClearer.get_team_cache_keys_and_controllers(affected_refs) @classmethod def postDeleteHook(cls, teams): # To run after the team has been deleted. ...
from backend.common.manipulators.manipulator_base import ManipulatorBase from backend.common.models.team import Team class TeamManipulator(ManipulatorBase[Team]):
32
124
416
9
22
guineawheek/ftc-data-take-2
src/backend/common/manipulators/team_manipulator.py
Python
TeamManipulator
TeamManipulator
5
56
5
5
6f1634336e518a05e3834dc9e14ea0210aa2f2f1
bigcode/the-stack
train
9caf02558564571462711a86
train
class
@greenday_api.api_class( resource_name='video_tags', auth_level=endpoints.AUTH_LEVEL.REQUIRED) class VideoTagAPI(BaseAPI, ProjectAPIMixin): """ API to handle video tags. Object disposed after request is completed. """ def __init__(self, *args, **kwargs): """ Creates ...
@greenday_api.api_class( resource_name='video_tags', auth_level=endpoints.AUTH_LEVEL.REQUIRED) class VideoTagAPI(BaseAPI, ProjectAPIMixin):
""" API to handle video tags. Object disposed after request is completed. """ def __init__(self, *args, **kwargs): """ Creates the video tag API """ super(VideoTagAPI, self).__init__(*args, **kwargs) self.mapper = VideoTagMapper(VideoTagResponseMe...
.models import Q from greenday_core.api_exceptions import BadRequestException from greenday_core.models import ( Project, GlobalTag, ProjectTag, VideoTag, VideoTagInstance, Video ) from ..mapper import GeneralMapper from ..api import ( BaseAPI, greenday_api, greenday_method, auth_required ) from .....
256
256
2,732
36
219
meedan/montage
appengine/src/greenday_api/videotag/videotag_api.py
Python
VideoTagAPI
VideoTagAPI
44
387
44
46
2921b4c59e5a56243084a8778a69013d1a62ac51
bigcode/the-stack
train
5b577aaa5459caf27694db1d
train
function
def test_vegalite_output(): # TODO: somehow test that output is valid HTML/JS? spec_with_data = VEGALITE_SPEC.copy() spec_with_data['data'] = JSON_DATA # Test three ways of specifying data obj1 = VegaLite(VEGALITE_SPEC, PANDAS_DATA) obj2 = VegaLite(VEGALITE_SPEC, JSON_DATA['values']) obj3 =...
def test_vegalite_output(): # TODO: somehow test that output is valid HTML/JS?
spec_with_data = VEGALITE_SPEC.copy() spec_with_data['data'] = JSON_DATA # Test three ways of specifying data obj1 = VegaLite(VEGALITE_SPEC, PANDAS_DATA) obj2 = VegaLite(VEGALITE_SPEC, JSON_DATA['values']) obj3 = VegaLite(spec_with_data) js1 = obj1._generate_js(id='ABC', sort_keys=True) ...
"quantitative"}, "y": {"field": "y", "type": "quantitative"} } } # TODO: use an actual Vega spec VEGA_SPEC = VEGALITE_SPEC def test_vegalite_output(): # TODO: somehow test that output is valid HTML/JS?
64
64
159
22
41
xtianpoli/ipyvega
vega/tests/test_outputs.py
Python
test_vegalite_output
test_vegalite_output
29
42
29
30
f1198b93b94ab6e8faa6567483f4097de382e7d2
bigcode/the-stack
train
eaaaace7e36905e8e4001bad
train
function
def test_vega_output(): # TODO: use an actual vega spec data = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) obj = Vega(VEGA_SPEC, data) js = obj._generate_js(id='ABC')
def test_vega_output(): # TODO: use an actual vega spec
data = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) obj = Vega(VEGA_SPEC, data) js = obj._generate_js(id='ABC')
) js2 = obj2._generate_js(id='ABC', sort_keys=True) js3 = obj3._generate_js(id='ABC', sort_keys=True) assert js1 == js2 == js3 def test_vega_output(): # TODO: use an actual vega spec
64
64
71
18
45
xtianpoli/ipyvega
vega/tests/test_outputs.py
Python
test_vega_output
test_vega_output
45
49
45
46
9775a97d9cd066a664e83103d2f52e201dcfb41b
bigcode/the-stack
train
90c3b6078b119497afced582
train
class
class Provider(AddressProvider): """Provider for Faker which adds fake address with more specific locations.""" @staticmethod def get_location_info_csv(csv_file_name: str) -> List[str]: """ Get the location info from csv file. :param csv_file_name: CSV file name with the advanced or...
class Provider(AddressProvider):
"""Provider for Faker which adds fake address with more specific locations.""" @staticmethod def get_location_info_csv(csv_file_name: str) -> List[str]: """ Get the location info from csv file. :param csv_file_name: CSV file name with the advanced or custom location info :re...
coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 import os from typing import List, Any import pandas as pd from openpandemic import logger from faker.providers.address import Provider as AddressProvider localized = True class Provider(AddressProvider):
64
64
169
5
58
OpenPandemic/openpandemic-analytics
openpandemic/fake/providers/address/__init__.py
Python
Provider
Provider
17
40
17
17
db32dfdf27f76b4495c4234c9e3ebf394eb64155
bigcode/the-stack
train
bb6a4adcaa9308b72686e01b
train
class
class AdapterMeta(abc.ABCMeta): _available_: FrozenSet[str] _parse_replacements_: Dict[str, Callable] def __new__(mcls, name, bases, namespace, **kwargs): # mypy does not like the `**kwargs`. But `ABCMeta` itself takes # `**kwargs` in its argspec here (and passes them to `type.__new__`. ...
class AdapterMeta(abc.ABCMeta):
_available_: FrozenSet[str] _parse_replacements_: Dict[str, Callable] def __new__(mcls, name, bases, namespace, **kwargs): # mypy does not like the `**kwargs`. But `ABCMeta` itself takes # `**kwargs` in its argspec here (and passes them to `type.__new__`. # I'm not sure there is any...
**kwargs) if parse_replacement: available_function = self.parse(parse_replacement) else: available_function = self return available_function(inner) return wrapper def parse_none(self, func: Callable) -> Callable: wrapper = self....
115
115
385
9
106
kazanzhy/dbt-core
core/dbt/adapters/base/meta.py
Python
AdapterMeta
AdapterMeta
92
128
92
92
2d978b7bf2baa0757b1c2e6fdf438d344e4d6952
bigcode/the-stack
train
1c314d35f4480abe067311b1
train
class
class _Available: def __call__(self, func: Callable) -> Callable: func._is_available_ = True # type: ignore return func def parse(self, parse_replacement: Callable) -> Decorator: """A decorator factory to indicate that a method on the adapter will be exposed to the database wra...
class _Available:
def __call__(self, func: Callable) -> Callable: func._is_available_ = True # type: ignore return func def parse(self, parse_replacement: Callable) -> Decorator: """A decorator factory to indicate that a method on the adapter will be exposed to the database wrapper, and will be ...
import abc from functools import wraps from typing import Callable, Optional, Any, FrozenSet, Dict, Set from dbt.deprecations import warn, renamed_method Decorator = Callable[[Any], Callable] class _Available:
48
163
546
4
44
kazanzhy/dbt-core
core/dbt/adapters/base/meta.py
Python
_Available
_Available
11
86
11
11
7a022a37c02c6eed84b0524211d6431dbeef4ef5
bigcode/the-stack
train
e8918a8c611324db848a7065
train
function
def _test_model( cls ): A = cls() A.elaborate() A.apply( GenDAGPass() ) A.apply( SimpleSchedulePass() ) A.apply( PrepareSimPass() ) A.sim_reset() A.sim_eval_combinational() T = 0 while T < 5: A.sim_tick() T += 1 return A
def _test_model( cls ):
A = cls() A.elaborate() A.apply( GenDAGPass() ) A.apply( SimpleSchedulePass() ) A.apply( PrepareSimPass() ) A.sim_reset() A.sim_eval_combinational() T = 0 while T < 5: A.sim_tick() T += 1 return A
32, bitstruct from pymtl3.dsl import * from pymtl3.dsl.errors import UpblkCyclicError from ..GenDAGPass import GenDAGPass from ..PrepareSimPass import PrepareSimPass from ..SimpleSchedulePass import SimpleSchedulePass def _test_model( cls ):
64
64
87
7
56
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
_test_model
_test_model
17
31
17
17
dc21a40056832000370d2203391bb39ddc4025c6
bigcode/the-stack
train
66c6c4ab9ec18a1a8fbf938b
train
function
def _test_combinational_loop(): class Top(Component): def construct( s ): s.a = Wire(int) s.b = Wire(int) s.c = Wire(int) s.d = Wire(int) @update def up1(): s.b = s.d + 1 @update def up2(): s.c = s.b + 1 @update def up3(): s....
def _test_combinational_loop():
class Top(Component): def construct( s ): s.a = Wire(int) s.b = Wire(int) s.c = Wire(int) s.d = Wire(int) @update def up1(): s.b = s.d + 1 @update def up2(): s.c = s.b + 1 @update def up3(): s.d = s.c + 1 print("up3 pr...
, s.j ) try: _test_model( Top ) except UpblkCyclicError as e: print("{} is thrown\n{}".format( e.__class__.__name__, e )) return raise Exception("Should've thrown UpblkCyclicError.") def _test_combinational_loop():
65
65
218
8
57
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
_test_combinational_loop
_test_combinational_loop
101
136
101
102
f9dd7326bd19cdb0024b17a942366903b0b6235a
bigcode/the-stack
train
1a45ded8cc7791373cae08d6
train
function
def test_very_deep_dag(): class Inner(Component): def construct( s ): s.in_ = InPort(32) s.out = OutPort(32) @update def up(): s.out @= s.in_ + 1 def done( s ): return True def line_trace( s ): return "{} > {}".format( s.a, s.b ) class Top(Component): ...
def test_very_deep_dag():
class Inner(Component): def construct( s ): s.in_ = InPort(32) s.out = OutPort(32) @update def up(): s.out @= s.in_ + 1 def done( s ): return True def line_trace( s ): return "{} > {}".format( s.a, s.b ) class Top(Component): def construct( s, N=2000 )...
.d ) try: _test_model( Top ) except UpblkCyclicError as e: print("{} is thrown\n{}".format( e.__class__.__name__, e )) return raise Exception("Should've thrown UpblkCyclicError.") def test_very_deep_dag():
64
64
174
9
55
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
test_very_deep_dag
test_very_deep_dag
138
166
138
139
c033a156aa2df02cb0082463d3d1be4df62cc168
bigcode/the-stack
train
fa2db36d79e4b0c80aa4be58
train
function
def test_const_connect_nested_struct_signal_to_struct(): @bitstruct class SomeMsg1: a: Bits8 b: Bits32 @bitstruct class SomeMsg2: a: SomeMsg1 b: Bits32 class Top( Component ): def construct( s ): s.out = OutPort(SomeMsg2) connect( s.out, SomeMsg2(SomeMsg1(1,2),3) ) x = To...
def test_const_connect_nested_struct_signal_to_struct(): @bitstruct
class SomeMsg1: a: Bits8 b: Bits32 @bitstruct class SomeMsg2: a: SomeMsg1 b: Bits32 class Top( Component ): def construct( s ): s.out = OutPort(SomeMsg2) connect( s.out, SomeMsg2(SomeMsg1(1,2),3) ) x = Top() x.elaborate() x.apply( GenDAGPass() ) x.apply( SimpleSchedule...
def sx(): s.x @= 10 def line_trace( s ): return f"{s.x}" # with @=, we don't have the subscript exception anymore _test_model( Top ) def test_const_connect_nested_struct_signal_to_struct(): @bitstruct
64
64
174
15
49
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
test_const_connect_nested_struct_signal_to_struct
test_const_connect_nested_struct_signal_to_struct
216
242
216
218
ccac600fe5772085133f3dc4d2613888f547a210
bigcode/the-stack
train
c614bf5f1310c0d8f6a50f74
train
function
def test_equal_top_level(): class A(Component): def construct( s ): @update def up(): print(1) a = A() a.apply( GenDAGPass() ) a.apply( SimpleSchedulePass() ) a.apply( PrepareSimPass() ) a.sim_reset() try: a.reset = 0 a.sim_tick() except AssertionError as e: print(e...
def test_equal_top_level():
class A(Component): def construct( s ): @update def up(): print(1) a = A() a.apply( GenDAGPass() ) a.apply( SimpleSchedulePass() ) a.apply( PrepareSimPass() ) a.sim_reset() try: a.reset = 0 a.sim_tick() except AssertionError as e: print(e) assert str(e).startswi...
AGPass() ) x.apply( SimpleSchedulePass() ) x.apply( PrepareSimPass() ) x.sim_reset() x.sim_eval_combinational() x.sim_tick() assert x.out == SomeMsg2(SomeMsg1(1,2),3) def test_equal_top_level():
64
64
115
6
58
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
test_equal_top_level
test_equal_top_level
244
263
244
244
70bbc478a7ed4962d4ecbd6223b9dcb579c2b82c
bigcode/the-stack
train
2ad29cda9a73215af3d2a0c8
train
function
def test_connect_slice_int(): class Top( Component ): def construct( s ): from pymtl3.datatypes import Bits8, Bits32 s.y = OutPort( Bits8 ) s.x = Wire( Bits32 ) s.y //= s.x[0:8] @update def sx(): s.x @= 10 def line_trace( s ): return f"{s.x}" # with @=, ...
def test_connect_slice_int():
class Top( Component ): def construct( s ): from pymtl3.datatypes import Bits8, Bits32 s.y = OutPort( Bits8 ) s.x = Wire( Bits32 ) s.y //= s.x[0:8] @update def sx(): s.x @= 10 def line_trace( s ): return f"{s.x}" # with @=, we don't have the subscript exc...
s ): return True def line_trace( s ): return "b {} | c {}" \ .format( s.b, s.c ) A = _test_model( Top ) assert A.c > 5, "Is the sequential behavior actually captured?" def test_connect_slice_int():
64
64
115
6
58
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
test_connect_slice_int
test_connect_slice_int
197
214
197
198
ecdf9b295fa4b41c7899df1a1cb14fc1364da84c
bigcode/the-stack
train
19b072c1a96110f8a933540e
train
function
def test_sequential_break_loop(): class Top(Component): def construct( s ): s.b = Wire( Bits32 ) s.c = Wire( Bits32 ) @update def up1(): s.b @= s.c + 1 @update_ff def up2(): if s.reset: s.c <<= 0 else: s.c <<= s.b + 1 def don...
def test_sequential_break_loop():
class Top(Component): def construct( s ): s.b = Wire( Bits32 ) s.c = Wire( Bits32 ) @update def up1(): s.b @= s.c + 1 @update_ff def up2(): if s.reset: s.c <<= 0 else: s.c <<= s.b + 1 def done( s ): return True def ...
(N) ] for i in range(N-1): s.inners[i].out //= s.inners[i+1].in_ def done( s ): return True def line_trace( s ): return "" _test_model( Top ) def test_sequential_break_loop():
64
64
153
7
57
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
test_sequential_break_loop
test_sequential_break_loop
168
195
168
169
5386a0ce3949b16eb606caeab097f5a0368eefef
bigcode/the-stack
train
9d2a91445ed4e701a4a94c3d
train
function
def _test_false_cyclic_dependency(): class Top(Component): def construct( s ): s.a = Wire(int) s.b = Wire(int) s.c = Wire(int) s.d = Wire(int) s.e = Wire(int) s.f = Wire(int) s.g = Wire(int) s.h = Wire(int) s.i = Wire(int) s.j = Wire(int) @updat...
def _test_false_cyclic_dependency():
class Top(Component): def construct( s ): s.a = Wire(int) s.b = Wire(int) s.c = Wire(int) s.d = Wire(int) s.e = Wire(int) s.f = Wire(int) s.g = Wire(int) s.h = Wire(int) s.i = Wire(int) s.j = Wire(int) @update def up1(): s.a = 10 + ...
ate() A.apply( GenDAGPass() ) A.apply( SimpleSchedulePass() ) A.apply( PrepareSimPass() ) A.sim_reset() A.sim_eval_combinational() T = 0 while T < 5: A.sim_tick() T += 1 return A # SimpleSchedulePass statically schedules the blocks and hence cannot # figure out cyclic dependency that is not a...
124
124
414
8
116
kevinyuan/pymtl3
pymtl3/passes/sim/test/SimpleSchedulePass_test.py
Python
_test_false_cyclic_dependency
_test_false_cyclic_dependency
38
99
38
39
fd6fc5499e8d5d07f0b62b3422f6b13c228b42a4
bigcode/the-stack
train
c171495dbbdba9a772a469cc
train
class
class StableRadOptProblem(MoleculeTFAlphaZeroProblem): def __init__(self, engine: 'sqlalchemy.engine.Engine', builder: 'MoleculeBuilder', stability_model: 'tf.keras.Model', redox_model: 'tf.keras.Model', bde_model: 'tf.keras.Model'...
class StableRadOptProblem(MoleculeTFAlphaZeroProblem):
def __init__(self, engine: 'sqlalchemy.engine.Engine', builder: 'MoleculeBuilder', stability_model: 'tf.keras.Model', redox_model: 'tf.keras.Model', bde_model: 'tf.keras.Model', initial_state: str, ...
lmolecule.molecule.molecule_problem import MoleculeTFAlphaZeroProblem from rlmolecule.molecule.molecule_state import MoleculeState from rlmolecule.sql.run_config import RunConfig from rlmolecule.tree_search.metrics import collect_metrics from rlmolecule.tree_search.reward import RankedRewardFactory @tf.function(exper...
256
256
1,191
12
243
harrysorensennrel/rlmolecule
examples/stable_radical_optimization/stable_radical_problem.py
Python
StableRadOptProblem
StableRadOptProblem
43
160
43
43
3b4aa4554cb9d4acba12a73c79c1214e85ff1473
bigcode/the-stack
train
466b07aadd726109b22bbade
train
function
def construct_problem(run_config: RunConfig, stability_model: pathlib.Path, redox_model: pathlib.Path, bde_model: pathlib.Path, **kwargs): stability_model = tf.keras.models.load_model(stability_model, compile=False) redox_model = tf.keras.models.load_model(redox_model, compile=False) b...
def construct_problem(run_config: RunConfig, stability_model: pathlib.Path, redox_model: pathlib.Path, bde_model: pathlib.Path, **kwargs):
stability_model = tf.keras.models.load_model(stability_model, compile=False) redox_model = tf.keras.models.load_model(redox_model, compile=False) bde_model = tf.keras.models.load_model(bde_model, compile=False) prob_config = run_config.problem_config initial_state = prob_config.get('initial_state',...
.molecule) model_inputs = bde_get_inputs(bde_inputs.mol_smiles) pred_bdes = predict(self.bde_model, model_inputs) pred_bdes = pred_bdes[0][0, :, 0].numpy() bde_radical = pred_bdes[bde_inputs.bond_index] if len(bde_inputs.other_h_bonds) == 0: bde_diff = 30. # Just ...
181
181
606
33
147
harrysorensennrel/rlmolecule
examples/stable_radical_optimization/stable_radical_problem.py
Python
construct_problem
construct_problem
163
221
163
164
6e1bd423614a93030ff3263313dce7ff1f568836
bigcode/the-stack
train
99f15ef0e70e6df05558c413
train
function
def windowed_loss(target: float, desired_range: Tuple[float, float]) -> float: """ Returns 0 if the molecule is in the middle of the desired range, scaled loss otherwise. """ span = desired_range[1] - desired_range[0] lower_lim = desired_range[0] + span / 6 upper_lim = desired_range[1] - span / 6 ...
def windowed_loss(target: float, desired_range: Tuple[float, float]) -> float:
""" Returns 0 if the molecule is in the middle of the desired range, scaled loss otherwise. """ span = desired_range[1] - desired_range[0] lower_lim = desired_range[0] + span / 6 upper_lim = desired_range[1] - span / 6 if target < lower_lim: return max(1 - 3 * (abs(target - lower_lim)...
import collect_metrics from rlmolecule.tree_search.reward import RankedRewardFactory @tf.function(experimental_relax_shapes=True) def predict(model: 'tf.keras.Model', inputs): return model.predict_step(inputs) def windowed_loss(target: float, desired_range: Tuple[float, float]) -> float:
64
64
153
20
44
harrysorensennrel/rlmolecule
examples/stable_radical_optimization/stable_radical_problem.py
Python
windowed_loss
windowed_loss
26
40
26
26
112cc7784a04232f8ce0c1a16d306888f655126e
bigcode/the-stack
train
71c0257c9cf450cbdb0e660f
train
function
@tf.function(experimental_relax_shapes=True) def predict(model: 'tf.keras.Model', inputs): return model.predict_step(inputs)
@tf.function(experimental_relax_shapes=True) def predict(model: 'tf.keras.Model', inputs):
return model.predict_step(inputs)
olecule.molecule_state import MoleculeState from rlmolecule.sql.run_config import RunConfig from rlmolecule.tree_search.metrics import collect_metrics from rlmolecule.tree_search.reward import RankedRewardFactory @tf.function(experimental_relax_shapes=True) def predict(model: 'tf.keras.Model', inputs):
64
64
28
21
42
harrysorensennrel/rlmolecule
examples/stable_radical_optimization/stable_radical_problem.py
Python
predict
predict
21
23
21
22
d6a5cb446282821e4a403dde386c0ae959a4110c
bigcode/the-stack
train
c93989406aff64d344bc8e66
train
class
class TestMessageBackend(object): """Message backend for testing""" def __init__(self, *ka, **kw): self.messages = [] def add(self, *ka, **kw): self.messages.append((ka, kw))
class TestMessageBackend(object):
"""Message backend for testing""" def __init__(self, *ka, **kw): self.messages = [] def add(self, *ka, **kw): self.messages.append((ka, kw))
_poor): self.assertEqual(func(*args), result_rich) self.urls = self.poor_urls self._urlconf_setup() self.assertEqual(func(*args), result_poor) self.urls = self.rich_urls self._urlconf_setup() class TestMessageBackend(object):
64
64
51
6
58
APSL/django-blog-zinnia
zinnia/tests/test_admin.py
Python
TestMessageBackend
TestMessageBackend
62
68
62
62
f50956c3aca3d87b21748fa3e3fce70395b74feb
bigcode/the-stack
train
38e2c326e9e8321102802cb2
train
class
@skipIfCustomUser class EntryAdminTestCase(BaseAdminTestCase): """Test case for Entry Admin""" model_class = Entry admin_class = EntryAdmin def setUp(self): super(EntryAdminTestCase, self).setUp() params = {'title': 'My title', 'content': 'My content', ...
@skipIfCustomUser class EntryAdminTestCase(BaseAdminTestCase):
"""Test case for Entry Admin""" model_class = Entry admin_class = EntryAdmin def setUp(self): super(EntryAdminTestCase, self).setUp() params = {'title': 'My title', 'content': 'My content', 'slug': 'my-title'} self.entry = Entry.objects.create...
= None def setUp(self): disconnect_entry_signals() activate('en') self.site = AdminSite() self.admin = self.admin_class( self.model_class, self.site) def tearDown(self): """ Be sure to restore the good urls to use if a test fail before resto...
256
256
3,096
16
240
APSL/django-blog-zinnia
zinnia/tests/test_admin.py
Python
EntryAdminTestCase
EntryAdminTestCase
71
402
71
72
e2d647a25a82ebbea103014ae232482b4de6d736
bigcode/the-stack
train
8559ed5b6f1962025f20642d
train
class
class BaseAdminTestCase(TestCase): rich_urls = 'zinnia.tests.implementations.urls.default' poor_urls = 'zinnia.tests.implementations.urls.poor' urls = rich_urls model_class = None admin_class = None def setUp(self): disconnect_entry_signals() activate('en') self.site = A...
class BaseAdminTestCase(TestCase):
rich_urls = 'zinnia.tests.implementations.urls.default' poor_urls = 'zinnia.tests.implementations.urls.poor' urls = rich_urls model_class = None admin_class = None def setUp(self): disconnect_entry_signals() activate('en') self.site = AdminSite() self.admin = sel...
from zinnia.models.category import Category from zinnia.tests.utils import datetime from zinnia.admin.entry import EntryAdmin from zinnia.admin.category import CategoryAdmin from zinnia.signals import disconnect_entry_signals from zinnia.url_shortener.backends.default import base36 class BaseAdminTestCase(TestCase):
72
72
243
8
63
APSL/django-blog-zinnia
zinnia/tests/test_admin.py
Python
BaseAdminTestCase
BaseAdminTestCase
25
59
25
25
2848e9d03abf017359a79d044552525679c32691
bigcode/the-stack
train
f1eef9dc3c1086b836666629
train
class
class CategoryAdminTestCase(BaseAdminTestCase): """Test cases for Category Admin""" model_class = Category admin_class = CategoryAdmin def test_get_tree_path(self): category = Category.objects.create(title='Category', slug='cat') self.check_with_rich_and_poor_urls( self.adm...
class CategoryAdminTestCase(BaseAdminTestCase):
"""Test cases for Category Admin""" model_class = Category admin_class = CategoryAdmin def test_get_tree_path(self): category = Category.objects.create(title='Category', slug='cat') self.check_with_rich_and_poor_urls( self.admin.get_tree_path, (category,), '<a h...
/js/prepopulate.min.js', '/static/zinnia/js/jquery.js', '/static/zinnia/js/jquery.bgiframe.js', '/static/zinnia/js/jquery.autocomplete.js', '/admin/zinnia/entry/autocomplete_tags/']) class CategoryAdminTestCase(BaseAdminTestCase):
63
64
97
10
53
APSL/django-blog-zinnia
zinnia/tests/test_admin.py
Python
CategoryAdminTestCase
CategoryAdminTestCase
405
416
405
405
7e5599220a595b17b8fd729056bbcabfc3a162a3
bigcode/the-stack
train
5dcba64f96866845a3bd78d1
train
function
def wa_user_host(): parser = argparse.ArgumentParser(description="Get mapping for user and host from wa-ssh configuration files") parser.add_argument("user_at_host", help="A pointer to a configuration or a direct reference in the form user@hostname") parser.add_argument("-c", "--config", help="Configuration...
def wa_user_host():
parser = argparse.ArgumentParser(description="Get mapping for user and host from wa-ssh configuration files") parser.add_argument("user_at_host", help="A pointer to a configuration or a direct reference in the form user@hostname") parser.add_argument("-c", "--config", help="Configuration file", nargs="*") ...
user, host, keyserver = map_user_at_host(args.config, args.user_at_host) key = get_privkey(args.config, host, user, keyserver) if key: print(key) else: print("No response") sys.exit(1) def wa_user_host():
64
64
111
5
59
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
wa_user_host
wa_user_host
48
54
48
48
69f8e62954129f748fa8d4094eb6958c5835ca5c
bigcode/the-stack
train
2243289308b72ac7dca08ed2
train
function
def map_user_at_host(extra_confs, user_at_host): pattern = re.compile("([^@]*)@(.*)") match = pattern.match(user_at_host) if match: user = match.group(1) host = match.group(2) else: user = None host = user_at_host return map_user_host(extra_confs, user, host)
def map_user_at_host(extra_confs, user_at_host):
pattern = re.compile("([^@]*)@(.*)") match = pattern.match(user_at_host) if match: user = match.group(1) host = match.group(2) else: user = None host = user_at_host return map_user_host(extra_confs, user, host)
"--config", help="Configuration file", nargs="*") args = parser.parse_args() mapped_user, mapped_host, _ = map_user_at_host(args.config, args.user_at_host) print(mapped_user + " " + mapped_host) def map_user_at_host(extra_confs, user_at_host):
64
64
82
13
51
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
map_user_at_host
map_user_at_host
56
65
56
56
acd5344666da6bd57fc79fa2262c708b7c503556
bigcode/the-stack
train
05af206356365ab19d9c7fda
train
function
def wa_pubkeys(): parser = argparse.ArgumentParser(description="Fetch public keys") parser.add_argument("host", help="The host that requests keys for login") parser.add_argument("username", help="The user that requests keys for login") parser.add_argument("-c", "--config", help="Configuration file", nar...
def wa_pubkeys():
parser = argparse.ArgumentParser(description="Fetch public keys") parser.add_argument("host", help="The host that requests keys for login") parser.add_argument("username", help="The user that requests keys for login") parser.add_argument("-c", "--config", help="Configuration file", nargs="*") args =...
browser import time import json import urllib.request, urllib.parse, urllib.error from wa_ssh import load_config from requests import get from wa_ssh.utils import get_query_param, get_open_port, stdchannel_redirected KEY_RESPONSE = None SERVER = None def wa_pubkeys():
64
64
121
5
58
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
wa_pubkeys
wa_pubkeys
24
33
24
24
b50c647a1030113705d18806f61022f697768d85
bigcode/the-stack
train
2b5769cbf0476451edf241f3
train
class
class KeyResponseHandler(http.server.BaseHTTPRequestHandler): def _set_headers(self, status=200): self.send_response(status) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: ...
class KeyResponseHandler(http.server.BaseHTTPRequestHandler):
def _set_headers(self, status=200): self.send_response(status) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: try: self.wfile.write(f.encode()) ...
<html> <head><title>Key received</title></head> <body> <p>Key received, you may close this window.</p> <script> window.close(); </script> </body> </html>""" class KeyResponseHandler(http.server.BaseHTTPRequestHandler):
64
64
216
10
54
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
KeyResponseHandler
KeyResponseHandler
126
160
126
126
64bf3082f1b6823d5df2d82dd0e540dea19dd795
bigcode/the-stack
train
21829b0ee5bee5b4c55bda9d
train
function
def wa_privkey(): parser = argparse.ArgumentParser(description="Fetch private key") parser.add_argument("user_at_host", help="The host that requests keys for login") parser.add_argument("-c", "--config", help="Configuration file", nargs="*") args = parser.parse_args() user, host, keyserver = map_use...
def wa_privkey():
parser = argparse.ArgumentParser(description="Fetch private key") parser.add_argument("user_at_host", help="The host that requests keys for login") parser.add_argument("-c", "--config", help="Configuration file", nargs="*") args = parser.parse_args() user, host, keyserver = map_user_at_host(args.con...
="Configuration file", nargs="*") args = parser.parse_args() conf = load_config(extra_confs=args.config) url = conf['keyserver'] + "/pubkey/" + args.host + "/" + args.username resp = get(url) print(resp.content) def wa_privkey():
64
64
121
5
59
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
wa_privkey
wa_privkey
35
46
35
35
aeeb53fd054ceb528e840c8df02f98d9fbcc4a15
bigcode/the-stack
train
d4475c9405ed7cffc337e6c1
train
function
def get_privkey(extra_confs, host, username, keyserver): global SERVER port = get_open_port() Handler = KeyResponseHandler SERVER = socketserver.TCPServer(("127.0.0.1", port), Handler) url = keyserver + "/privkey/" + host + "/" + username + "?port=" + str(port) with stdchannel_redirected(sys.std...
def get_privkey(extra_confs, host, username, keyserver):
global SERVER port = get_open_port() Handler = KeyResponseHandler SERVER = socketserver.TCPServer(("127.0.0.1", port), Handler) url = keyserver + "/privkey/" + host + "/" + username + "?port=" + str(port) with stdchannel_redirected(sys.stdout, os.devnull): webbrowser.open(url, new=2, aut...
_user = user if not mapped_host: mapped_host = host if not keyserver: raise Exception("Failed to find a keyserver for host " + host) return mapped_user, mapped_host, keyserver def get_privkey(extra_confs, host, username, keyserver):
64
64
147
15
48
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
get_privkey
get_privkey
96
113
96
96
4d0550e95b17eb87c6f6a233af9414b40b157d47
bigcode/the-stack
train
501599c565e1a536109258cc
train
function
def map_user_host(extra_confs, user, host): conf = load_config(extra_confs=extra_confs) mapped_host = None mapped_user = None keyserver = None if "keyserver" in conf: keyserver = conf["keyserver"] if "hosts" in conf: for conf_host, host_conf in conf["hosts"].items(): ...
def map_user_host(extra_confs, user, host):
conf = load_config(extra_confs=extra_confs) mapped_host = None mapped_user = None keyserver = None if "keyserver" in conf: keyserver = conf["keyserver"] if "hosts" in conf: for conf_host, host_conf in conf["hosts"].items(): matches = False try: ...
.*)") match = pattern.match(user_at_host) if match: user = match.group(1) host = match.group(2) else: user = None host = user_at_host return map_user_host(extra_confs, user, host) def map_user_host(extra_confs, user, host):
71
71
239
12
59
NitorCreations/web-auth-ssh
wa_ssh/cli.py
Python
map_user_host
map_user_host
67
94
67
67
af68bb256abb29164ca5ee3be4ad1c7a06527978
bigcode/the-stack
train
e636c12fd48761a5bfdefc06
train
function
@pytest.mark.version('>=2.5') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.execute() assert act_1.clean_stdout == act_1.clean_expected_stdout
@pytest.mark.version('>=2.5') def test_1(act_1: Action):
act_1.expected_stdout = expected_stdout_1 act_1.execute() assert act_1.clean_stdout == act_1.clean_expected_stdout
400 result-2 S4 P4 300 result-2 S4 P5 400 result-2 S3 <null> <null> """ @pytest.mark.version('>=2.5') def test_1(act_1: Action):
64
64
52
19
45
FirebirdSQL/firebird-qa
tests/functional/gtcs/test_gtcs_proc_isql_20.py
Python
test_1
test_1
75
79
75
76
09dfd695168de90cf4998fcdcfa6d8b55335270b
bigcode/the-stack
train
217860ca04365d1a7c10c4cb
train
function
def downgrade(): op.drop_column('issues', 'extra')
def downgrade():
op.drop_column('issues', 'extra')
= 'b5cc62f79980' down_revision = '1cf31ab18f84' branch_labels = None depends_on = None def upgrade(): op.add_column('issues', sa.Column('extra', postgresql.JSONB(astext_type=sa.Text()), nullable=True)) def downgrade():
64
64
13
3
61
fossabot/kraken-3
server/kraken/migrations/versions/b5cc62f79980_add_extra_to_issue.py
Python
downgrade
downgrade
23
24
23
23
c692ebdae0ad389ee99b0326964207734ecc42b7
bigcode/the-stack
train
11f3428359b9c7d5d9f37792
train
function
def upgrade(): op.add_column('issues', sa.Column('extra', postgresql.JSONB(astext_type=sa.Text()), nullable=True))
def upgrade():
op.add_column('issues', sa.Column('extra', postgresql.JSONB(astext_type=sa.Text()), nullable=True))
ic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'b5cc62f79980' down_revision = '1cf31ab18f84' branch_labels = None depends_on = None def upgrade():
64
64
29
3
60
fossabot/kraken-3
server/kraken/migrations/versions/b5cc62f79980_add_extra_to_issue.py
Python
upgrade
upgrade
19
20
19
19
bc7e4319fd6d9833999e32e74ba23f5fd698616b
bigcode/the-stack
train
850647d327c941b0c753c299
train
class
class Column: """ Representation of a column in a row set. Contained by `RowSet` instances. """ __slots__ = ['table', 'name', 'ty'] def __init__(self, table: 'Identifier', name: 'Identifier', ty: 'Ty'): self.table = table self.name = name self.ty = ty
class Column:
""" Representation of a column in a row set. Contained by `RowSet` instances. """ __slots__ = ['table', 'name', 'ty'] def __init__(self, table: 'Identifier', name: 'Identifier', ty: 'Ty'): self.table = table self.name = name self.ty = ty
from typing import * if TYPE_CHECKING: from dropSQL.ast import Identifier, Ty class Column:
22
64
80
3
18
LakshyaaSoni/dropSQL
src/dropSQL/engine/column.py
Python
Column
Column
7
17
7
7
d03f17083fdbf31aacd7cecfc80fa2734163c195
bigcode/the-stack
train
34cde47bb132d9f562b4ec44
train
function
def Cleanse(obj, encoding='utf-8'): """Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Args: obj: Python data structure. encodi...
def Cleanse(obj, encoding='utf-8'):
"""Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Args: obj: Python data structure. encoding: Charset used to decode byte stri...
from __future__ import print_function import math from tensorboard import build_with_tf USE_TF = build_with_tf.use_tf() if USE_TF: import tensorflow as tf else: import tensorboard.utils as tf _INFINITY = float('inf') _NEGATIVE_INFINITY = float('-inf') def Cleanse(obj, encoding='utf-8'):
76
76
255
11
65
ml7/tensorboard
tensorboard/backend/json_util.py
Python
Cleanse
Cleanse
46
81
46
46
20c0f91f9b37a8ef629d169fac6faace51611a6e
bigcode/the-stack
train
e4ef295c9cec1b3f49916b8d
train
function
def try_connect(sockaddr): """Try to connect a UDP socket to the given address. "Connecting" a UDP socket means only setting the default destination for packets, so nothing is actually sent. Return True if the socket.connect() call was successful, False otherwise. For loopback this effectively test...
def try_connect(sockaddr):
"""Try to connect a UDP socket to the given address. "Connecting" a UDP socket means only setting the default destination for packets, so nothing is actually sent. Return True if the socket.connect() call was successful, False otherwise. For loopback this effectively tests if the address is really ...
assumption that those IPs are local a positive result means they should be usable for tests. The script prints the first two (in order of arguments) usable addresses to sys.stdout. IPv6 addresses in the output are enclosed in square brackets. """ import socket import sys def try_connect(sockaddr):
64
64
162
6
57
airtower-luna/mod_gnutls
test/check_test_ips.py
Python
try_connect
try_connect
32
51
32
32
9ecb4514ba4d981679031f2565d35bf4db0da67d
bigcode/the-stack
train
0f4c06d89e8b181e276bfb24
train
class
class ApiAppResouce(ModelResource): class Meta: queryset = ApiApp.objects.all() resource_name = 'apiapp' filtering = {'title': ALL}
class ApiAppResouce(ModelResource):
class Meta: queryset = ApiApp.objects.all() resource_name = 'apiapp' filtering = {'title': ALL}
from tastypie.resources import ModelResource from tastypie.constants import ALL from apiapp.models import ApiApp class ApiAppResouce(ModelResource):
34
64
37
9
24
BurhanH/api-app
SimpleAPIApp/api.py
Python
ApiAppResouce
ApiAppResouce
8
12
8
8
1bab8da6b46529751cf782c186d1be98af0ba8a9
bigcode/the-stack
train
7a92b0442984b3fb9108f855
train
class
class SslAdapter(HTTPAdapter): def __init__(self, cert, password=None, disable_validation=False, *args, **kwargs): self._certfile, self._keyfile = cert self._password = password self._disable_validation = disable_validation super(SslAdapter, self).__init__(*args, **k...
class SslAdapter(HTTPAdapter):
def __init__(self, cert, password=None, disable_validation=False, *args, **kwargs): self._certfile, self._keyfile = cert self._password = password self._disable_validation = disable_validation super(SslAdapter, self).__init__(*args, **kwargs) def init_poolmanage...
import ConfluenceSeraphAuthenticationFailedUrlError from .exceptions import ConfluenceSslError from .exceptions import ConfluenceTimeoutError from .std.confluence import API_REST_BIND_PATH from requests.adapters import HTTPAdapter import json import requests import ssl class SslAdapter(HTTPAdapter):
64
64
189
8
55
TheDubliner/confluencebuilder
sphinxcontrib/confluencebuilder/rest.py
Python
SslAdapter
SslAdapter
22
42
22
22
5a80162c6a537065cda7149cbb463262c88bc288
bigcode/the-stack
train
17640781ab9dfab569742aa4
train
class
class Rest: CONFLUENCE_DEFAULT_ENCODING = 'utf-8' def __init__(self, config): self.url = config.confluence_server_url self.session = self._setup_session(config) self.verbosity = config.sphinx_verbosity def _setup_session(self, config): session = requests.Session() s...
class Rest:
CONFLUENCE_DEFAULT_ENCODING = 'utf-8' def __init__(self, config): self.url = config.confluence_server_url self.session = self._setup_session(config) self.verbosity = config.sphinx_verbosity def _setup_session(self, config): session = requests.Session() session.heade...
fluenceProxyPermissionError from .exceptions import ConfluenceSeraphAuthenticationFailedUrlError from .exceptions import ConfluenceSslError from .exceptions import ConfluenceTimeoutError from .std.confluence import API_REST_BIND_PATH from requests.adapters import HTTPAdapter import json import requests import ssl clas...
256
256
1,639
3
253
TheDubliner/confluencebuilder
sphinxcontrib/confluencebuilder/rest.py
Python
Rest
Rest
44
237
44
44
851fb612d6151b35411eb8f709045b80c9d12e7c
bigcode/the-stack
train
83ca12c769168fa7f70b7e48
train
function
def map_parser(filename): edges = dict() nodes = dict() def add_edge(corr1, corr2): dist = int(sqrt((corr2[0] - corr1[0]) ** 2 + (corr2[1] - corr1[1]) ** 2)) label1 = nameify(corr1) label2 = nameify(corr2) d = edges.get(label1) if d: d[label2] = dist ...
def map_parser(filename):
edges = dict() nodes = dict() def add_edge(corr1, corr2): dist = int(sqrt((corr2[0] - corr1[0]) ** 2 + (corr2[1] - corr1[1]) ** 2)) label1 = nameify(corr1) label2 = nameify(corr2) d = edges.get(label1) if d: d[label2] = dist else: edge...
import sys import os.path DIR_PATH = os.path.dirname(__file__) sys.path.append(os.path.join(DIR_PATH, '..')) import csv from math import sqrt from search import Graph def map_parser(filename):
46
82
274
5
40
tmpethick/ai-search-visualization
gui/map_parser.py
Python
map_parser
map_parser
10
42
10
10
5378f9aa71944041a1eb704b26548530ec0c8b5d
bigcode/the-stack
train
cae75b79e10740d9e012e7e0
train
function
def ogr_shape_25(): layer_name = 'touchingrings2' wkt = 'MULTIPOLYGON(((10 5, 5 5,5 0,0 0,0 10,10 10,10 5)),((10 5,10 0,5 0,5 4.9,10 5)), ((100 100,100 200,200 200,200 100,100 100)))' geom = ogr.CreateGeometryFromWkt(wkt) if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.Expor...
def ogr_shape_25():
layer_name = 'touchingrings2' wkt = 'MULTIPOLYGON(((10 5, 5 5,5 0,0 0,0 10,10 10,10 5)),((10 5,10 0,5 0,5 4.9,10 5)), ((100 100,100 200,200 200,200 100,100 100)))' geom = ogr.CreateGeometryFromWkt(wkt) if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUn...
' geom = ogr.CreateGeometryFromWkt(wkt) if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': gdaltest.post_reason( 'Test for layer %s failed' % layer_name ) return 'fail' return 'success' ################################...
121
121
405
6
115
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_25
ogr_shape_25
1,076
1,097
1,076
1,076
cad67c9ec4220da0546d4375ec297e0c377caac3
bigcode/the-stack
train
2c2856e12e87bb3c794094f0
train
function
def ogr_shape_87(): ds = ogr.Open('data/weird_header_length.dbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField(0) != 1: return 'fail' return 'success'
def ogr_shape_87():
ds = ogr.Open('data/weird_header_length.dbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField(0) != 1: return 'fail' return 'success'
Feature() val = f.GetField(0) ds.ReleaseResultSet(sql_lyr) if val != 6: return 'fail' return 'success' ############################################################################### # Check we accept opening standalone .dbf files with weird header lengths (#6035) def ogr_shape_87():
64
64
59
6
58
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_87
ogr_shape_87
4,118
4,126
4,118
4,119
82a9835de0b261883506daf9e2b9850275e78980
bigcode/the-stack
train
00c19c2c5af8530ef0d538f5
train
function
def ogr_shape_93(): ds = ogr.Open('data/pointz_without_m.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() wkt = f.GetGeometryRef().ExportToIsoWkt() if wkt != 'POINT Z (1 2 3)': gdaltest.post_reason('fail') print(wkt) return 'fail' return 'success'
def ogr_shape_93():
ds = ogr.Open('data/pointz_without_m.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() wkt = f.GetGeometryRef().ExportToIsoWkt() if wkt != 'POINT Z (1 2 3)': gdaltest.post_reason('fail') print(wkt) return 'fail' return 'success'
wkt != 'MULTIPOINT Z ((0 1 2),(3 4 5))': gdaltest.post_reason('fail') print(wkt) return 'fail' return 'success' ############################################################################### # Test reading point Z geometries without M def ogr_shape_93():
64
64
93
6
57
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_93
ogr_shape_93
4,286
4,297
4,286
4,287
4e0210b7a9a4c4202c0b667acf46c42e52e48d3f
bigcode/the-stack
train
2e99d6b4646869844c6f01b8
train
function
def ogr_shape_79(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_79.dbf') lyr = ds.CreateLayer('ogr_shape_79') # This will create a (for now) invisible 'FID' field lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) # This will delete the implicit field fd = o...
def ogr_shape_79():
ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_79.dbf') lyr = ds.CreateLayer('ogr_shape_79') # This will create a (for now) invisible 'FID' field lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) # This will delete the implicit field fd = ogr.FieldDefn('field1'...
f.GetField('dblfield') != 9007199254740992.: gdaltest.post_reason('did not get expected value') f.DumpReadable() return 'fail' ds = None return 'success' ############################################################################### # Test adding a field after creating features with ...
72
72
242
6
65
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_79
ogr_shape_79
3,762
3,790
3,762
3,763
ffa59c08e783e4d6a0574b6169b31cef35820cbf
bigcode/the-stack
train
96b5a20be8255add5ccbd305
train
function
def is_same(filename1, filename2, verbose = True): f1 = gdal.VSIFOpenL(filename1, "rb") if f1 is None: if verbose: print('%s does not exist' % filename1) return False f2 = gdal.VSIFOpenL(filename2, "rb") if f2 is None: if verbose: print('%s does not exist'...
def is_same(filename1, filename2, verbose = True):
f1 = gdal.VSIFOpenL(filename1, "rb") if f1 is None: if verbose: print('%s does not exist' % filename1) return False f2 = gdal.VSIFOpenL(filename2, "rb") if f2 is None: if verbose: print('%s does not exist' % filename2) gdal.VSIFCloseL(f1) r...
= gdal.VSIStatL('/vsimem/ogr_shape_106.shp').size if size != 188 + 2 * 8: gdaltest.post_reason('fail') print(size) return 'fail' shape_drv.DeleteDataSource( '/vsimem/ogr_shape_106.shp' ) return 'success' ############################################################################...
100
100
334
13
86
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
is_same
is_same
5,141
5,173
5,141
5,141
6bb5985ec1d9ee82f29dd8654ef63b4de4878bbe
bigcode/the-stack
train
f5833c9cea307d1caf8a2556
train
function
def ogr_shape_42(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: return 'skip' shutil.copy('data/poly.shp', 'tmp/poly.shp') shutil.copy('data/poly.shx', 'tmp/poly.shx') shutil.copy('data/poly.dbf', 'tmp/poly.dbf') ret = gdaltest.runexternal(test_cli_u...
def ogr_shape_42():
import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: return 'skip' shutil.copy('data/poly.shp', 'tmp/poly.shp') shutil.copy('data/poly.shx', 'tmp/poly.shx') shutil.copy('data/poly.dbf', 'tmp/poly.dbf') ret = gdaltest.runexternal(test_cli_utilities.get_test_ogr...
x') os.remove('tmp/poly.dbf') if ret.find('INFO') == -1 or ret.find('ERROR') != -1: print(ret) return 'fail' return 'success' ############################################################################### # Run test_ogrsf with -sql def ogr_shape_42():
64
64
176
6
57
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_42
ogr_shape_42
1,766
1,786
1,766
1,767
15a22245fb3d0b0f92c50a2e288e2d492212d93e
bigcode/the-stack
train
5b949534639e2758f632ee4e
train
function
def ogr_shape_100(): old_val = gdal.GetConfigOption('OGR_SHAPE_PACK_IN_PLACE') for variant in [ 'YES', 'NO' ]: ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_shape_100.shp') lyr = ds.CreateLayer('ogr_shape_100') lyr.CreateField( ogr.FieldDefn('foo', ogr.OFTString...
def ogr_shape_100():
old_val = gdal.GetConfigOption('OGR_SHAPE_PACK_IN_PLACE') for variant in [ 'YES', 'NO' ]: ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_shape_100.shp') lyr = ds.CreateLayer('ogr_shape_100') lyr.CreateField( ogr.FieldDefn('foo', ogr.OFTString) ) f = ogr.Fe...
ORITY["EPSG","9122"]], AUTHORITY["EPSG","4149"]], PROJECTION["Hotine_Oblique_Mercator_Azimuth_Center"], PARAMETER["latitude_of_center",46.95240555555556], PARAMETER["longitude_of_center",7.439583333333333], PARAMETER["azimuth",90], PARAMETER["rectified_grid_angle",90], PARAMETER["scale_f...
256
256
1,088
6
249
OpenGeoLabs/gdal
autotest/ogr/ogr_shape.py
Python
ogr_shape_100
ogr_shape_100
4,576
4,688
4,576
4,577
19429ccf0f4b6fa3591de70aeef4c5a53e126a07
bigcode/the-stack
train