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
d60c1f539de776c1f7d5f197
train
function
def test_create_new_file(): data = get_random_string().encode() path = default_storage.save('test1/test.txt', ContentFile(data)) assert default_storage.open(path).read() == data
def test_create_new_file():
data = get_random_string().encode() path = default_storage.save('test1/test.txt', ContentFile(data)) assert default_storage.open(path).read() == data
from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.utils.crypto import get_random_string def test_create_new_file():
33
64
43
6
26
martbln/django-service-boilerplate
_project_/tests/test_filestorage.py
Python
test_create_new_file
test_create_new_file
6
9
6
6
b28dbee3a12871961173fe8af4b20c7b397b6eb7
bigcode/the-stack
train
8f35874304ceb1bc2eaae85b
train
function
def get_tests(app_module): parts = app_module.__name__.split('.') prefix, last = parts[:-1], parts[-1] try: test_module = import_module('.'.join(prefix + [TEST_MODULE])) except ImportError: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a...
def get_tests(app_module):
parts = app_module.__name__.split('.') prefix, last = parts[:-1], parts[-1] try: test_module = import_module('.'.join(prefix + [TEST_MODULE])) except ImportError: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests.py that actually exi...
unittest from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule __all__ = ('DjangoTestSuiteRunner') # The module name for tests outside models.py TEST_MODULE = 'tests' doctestOutputChecker = OutputChecker() def get_tests(app_module):
64
64
199
6
58
akaariai/django-old
django/test/simple.py
Python
get_tests
get_tests
21
42
21
21
692e81772dd733e5362f2fc52ac542120fe1e211
bigcode/the-stack
train
f25c42d54d549951e34f9cf3
train
function
def reorder_suite(suite, classes): """ Reorders a test suite by test type. `classes` is a sequence of types All tests of type classes[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. """ class_count = len(classes) bins = [unittest...
def reorder_suite(suite, classes):
""" Reorders a test suite by test type. `classes` is a sequence of types All tests of type classes[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. """ class_count = len(classes) bins = [unittest.TestSuite() for i in range(class_c...
, unittest.TestSuite): partition_suite(test, classes, bins) else: for i in range(len(classes)): if isinstance(test, classes[i]): bins[i].addTest(test) break else: bins[-1].addTest(test) def reorder_suite(...
64
64
129
8
56
akaariai/django-old
django/test/simple.py
Python
reorder_suite
reorder_suite
178
192
178
178
10cbc6ba85a6c2c011be8bebc89bb1cfd53fc3b6
bigcode/the-stack
train
33ae78f86be86f760be08713
train
function
def build_test(label): """ Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts)...
def build_test(label):
""" Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts) > 3: raise Val...
pass # Check to see if a separate 'tests' module exists parallel to the # models module test_module = get_tests(app_module) if test_module: # Load unit and doctests in the tests.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if ha...
169
169
565
5
163
akaariai/django-old
django/test/simple.py
Python
build_test
build_test
87
153
87
87
955060287692bc91a5257c4c86d8618c3c8221ca
bigcode/the-stack
train
3a1c4d9e6e51aef68a8aa4c3
train
function
def partition_suite(suite, classes, bins): """ Partitions a test suite by test type. classes is a sequence of types bins is a sequence of TestSuites, one more than classes Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ for ...
def partition_suite(suite, classes, bins):
""" Partitions a test suite by test type. classes is a sequence of types bins is a sequence of TestSuites, one more than classes Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ for test in suite: if isinstance(test, ...
then we were given a bad test label. if not tests: raise ValueError("Test label '%s' does not refer to a test" % label) # Construct a suite out of the tests that matched. return unittest.TestSuite(tests) def partition_suite(suite, classes, bins):
64
64
141
10
54
akaariai/django-old
django/test/simple.py
Python
partition_suite
partition_suite
156
175
156
156
de524b86dad4afdd056dde4ba14b752ff5b296d6
bigcode/the-stack
train
267def3c9960ed0ceac8185a
train
function
def build_suite(app_module): """ Create a complete Django test suite for the provided application module. """ suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_mod...
def build_suite(app_module):
""" Create a complete Django test suite for the provided application module. """ suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_module, 'suite'): suite....
directory, or one level up if last == 'models': app_root = import_module('.'.join(prefix)) else: app_root = app_module if not module_has_submodule(app_root, TEST_MODULE): test_module = None else: # The module exists, so there must be an i...
93
93
313
6
86
akaariai/django-old
django/test/simple.py
Python
build_suite
build_suite
45
84
45
45
f24ee031e18fa45b9ed2061298f1484aad460617
bigcode/the-stack
train
84c7f2768fd78744866ebda5
train
class
class DjangoTestSuiteRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settin...
class DjangoTestSuiteRunner(object):
def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False unittest.ins...
]) return bins[0] def dependency_ordered(test_databases, dependencies): """Reorder test_databases into an order that honors the dependencies described in TEST_DEPENDENCIES. """ ordered_test_databases = [] resolved_databases = set() while test_databases: changed = False defe...
256
256
1,125
7
248
akaariai/django-old
django/test/simple.py
Python
DjangoTestSuiteRunner
DjangoTestSuiteRunner
233
374
233
233
92ef0c28854db45449dbaa31c756d27715ae8793
bigcode/the-stack
train
ed0a346d137e572170bee988
train
function
def dependency_ordered(test_databases, dependencies): """Reorder test_databases into an order that honors the dependencies described in TEST_DEPENDENCIES. """ ordered_test_databases = [] resolved_databases = set() while test_databases: changed = False deferred = [] while...
def dependency_ordered(test_databases, dependencies):
"""Reorder test_databases into an order that honors the dependencies described in TEST_DEPENDENCIES. """ ordered_test_databases = [] resolved_databases = set() while test_databases: changed = False deferred = [] while test_databases: signature, (db_name, alia...
class_count = len(classes) bins = [unittest.TestSuite() for i in range(class_count+1)] partition_suite(suite, classes, bins) for i in range(class_count): bins[0].addTests(bins[i+1]) return bins[0] def dependency_ordered(test_databases, dependencies):
72
72
242
10
62
akaariai/django-old
django/test/simple.py
Python
dependency_ordered
dependency_ordered
195
230
195
195
7f7bbdc0cd83e32e75d0b09066f7eacace4c9eb8
bigcode/the-stack
train
aa59737c7c0e51a1d6acf52d
train
class
class ModelAggregateFilter(CharFilter): def filter(self, qs, value): if value in EMPTY_VALUES: return qs y_column = getattr(self.model, value['y_column']) if value['y_func'] == 'count': y_func = func.count(y_column) elif value['y_func'] == 'sum': ...
class ModelAggregateFilter(CharFilter):
def filter(self, qs, value): if value in EMPTY_VALUES: return qs y_column = getattr(self.model, value['y_column']) if value['y_func'] == 'count': y_func = func.count(y_column) elif value['y_func'] == 'sum': y_func = func.sum(y_column) eli...
from sqlalchemy import func, sql from jet_bridge_base.filters.char_filter import CharFilter from jet_bridge_base.filters.filter import EMPTY_VALUES class ModelAggregateFilter(CharFilter):
35
64
165
7
27
bokal2/jet-bridge
packages/jet_bridge_base/jet_bridge_base/filters/model_aggregate.py
Python
ModelAggregateFilter
ModelAggregateFilter
7
30
7
8
b901b66b6759e2237808ff25f243080ad2fd7335
bigcode/the-stack
train
1c9ba913dbfd39737df6221b
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='StoryUser', fields=[ ('nim', models.CharField(max_length=8, primary_key=True, serialize=False)), ('username', models.Ch...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='StoryUser', fields=[ ('nim', models.CharField(max_length=8, primary_key=True, serialize=False)), ('username', models.CharField(max_length=20)), ...
# Generated by Django 3.1.3 on 2020-11-19 06:01 import akastories.models from django.db import migrations, models import django_resized.forms class Migration(migrations.Migration):
50
64
159
7
42
didithilmy/akademik-stories
backend/akastories/migrations/0001_initial.py
Python
Migration
Migration
8
26
8
9
20df6b727f4e2350691a45e43da4134cccaac343
bigcode/the-stack
train
aacd8a43acd817a2c9159936
train
class
class MatplotlibExamplesSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spi...
class MatplotlibExamplesSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod
def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes throug...
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class MatplotlibExamplesSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, ...
93
108
363
48
44
xzlmark/webspider
matplotlib_examples/matplotlib_examples/middlewares.py
Python
MatplotlibExamplesSpiderMiddleware
MatplotlibExamplesSpiderMiddleware
11
56
11
16
4c04b26ddfd12b0b8a3863f62874d128ca711f44
bigcode/the-stack
train
3f5d4b7d5376e74c03ad36c8
train
class
class MatplotlibExamplesDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create ...
class MatplotlibExamplesDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod
def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the d...
# that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class MatplotlibExamplesDownloaderMiddleware(object): # No...
105
105
350
48
57
xzlmark/webspider
matplotlib_examples/matplotlib_examples/middlewares.py
Python
MatplotlibExamplesDownloaderMiddleware
MatplotlibExamplesDownloaderMiddleware
59
103
59
64
6f70cdb2905e426d6358a8c5375a7fcd61516c40
bigcode/the-stack
train
213cde87caff2040936fd4b0
train
class
class TradeDealTest(TradeDealHandlerBase): """ order update push""" def on_recv_rsp(self, rsp_pb): ret, content = super(TradeDealTest, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print("TradeDealTest content={}".format(content)) return ret, content
class TradeDealTest(TradeDealHandlerBase):
""" order update push""" def on_recv_rsp(self, rsp_pb): ret, content = super(TradeDealTest, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print("TradeDealTest content={}".format(content)) return ret, content
_recv_rsp(self, rsp_pb): ret, content = super(TradeOrderTest, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print("* TradeOrderTest content={}\n".format(content)) return ret, content class TradeDealTest(TradeDealHandlerBase):
64
64
71
10
53
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
TradeDealTest
TradeDealTest
109
117
109
109
3ae311f77893f704299c017ba41d4fbcbfe9603c
bigcode/the-stack
train
3410594d308e4b6bf6f24399
train
class
class StockQuoteTest(StockQuoteHandlerBase): """ 获得报价推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(StockQuoteTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: logger.debug("StockQuoteTest: error, msg: %s" % content) ...
class StockQuoteTest(StockQuoteHandlerBase):
""" 获得报价推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(StockQuoteTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: logger.debug("StockQuoteTest: error, msg: %s" % content) return RET_ERROR, content # ...
# -*- coding: utf-8 -*- """ Examples for use the python functions: get push data """ from time import sleep from futu import * class StockQuoteTest(StockQuoteHandlerBase):
42
64
116
10
32
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
StockQuoteTest
StockQuoteTest
10
21
10
10
4d5de3fe1d7ae49d87f51f5e1626e6c8c6d22ab3
bigcode/the-stack
train
6c14f0b9b8ec01b40399bf69
train
class
class SysNotifyTest(SysNotifyHandlerBase): """sys notify""" def on_recv_rsp(self, rsp_pb): """receive response callback function""" ret_code, content = super(SysNotifyTest, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: main_type, sub_type, msg = content ...
class SysNotifyTest(SysNotifyHandlerBase):
"""sys notify""" def on_recv_rsp(self, rsp_pb): """receive response callback function""" ret_code, content = super(SysNotifyTest, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: main_type, sub_type, msg = content print("* SysNotify main_type='{}' sub_type...
[0] ask_content = contents[1] # print("* BrokerTest code \n", stock_code) # print("* BrokerTest bid \n", bid_content) # print("* BrokerTest ask \n", ask_content) return ret_code class SysNotifyTest(SysNotifyHandlerBase):
64
64
123
9
54
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
SysNotifyTest
SysNotifyTest
84
95
84
84
ee2d324b21be5b2a148e8372271ec45635355ebd
bigcode/the-stack
train
254b523be40cd68b599a37ed
train
function
def trade_hk_test(): ''' 港股交易测试 :return: ''' trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) trd_ctx.set_handler(TradeOrderTest()) trd_ctx.set_handler(TradeDealTest()) trd_ctx.start() # 交易请求必须先解锁 !!! pwd_unlock = '979899' print("* unlock_trade : {}\n"....
def trade_hk_test():
''' 港股交易测试 :return: ''' trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) trd_ctx.set_handler(TradeOrderTest()) trd_ctx.set_handler(TradeDealTest()) trd_ctx.start() # 交易请求必须先解锁 !!! pwd_unlock = '979899' print("* unlock_trade : {}\n".format(trd_ctx.unlock_...
0, 0))) print("* deal_list_query : {}\n".format(trd_ctx.deal_list_query(code="000979"))) print("* history_order_list_query : {}\n".format(trd_ctx.history_order_list_query(status_filter_list=[OrderStatus.FILLED_ALL, OrderStatus.FILLED_PART], code="512310", start="...
138
138
460
6
132
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
trade_hk_test
trade_hk_test
238
273
238
238
35eefb2f004d6b92c63a762d8bd8801a8dc23475
bigcode/the-stack
train
3f39bb65a5afa40c9b76f810
train
class
class OrderBookTest(OrderBookHandlerBase): """ 获得摆盘推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(OrderBookTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* OrderBookTest: error, msg: %s" % content) return RET...
class OrderBookTest(OrderBookHandlerBase):
""" 获得摆盘推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(OrderBookTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* OrderBookTest: error, msg: %s" % content) return RET_ERROR, content # print("* OrderBoo...
_rsp(rsp_pb) if ret_code != RET_OK: print("* TickerTest: error, msg: %s" % content) return RET_ERROR, content # print("* TickerTest\n", content) return RET_OK, content class OrderBookTest(OrderBookHandlerBase):
64
64
108
9
54
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
OrderBookTest
OrderBookTest
58
67
58
58
7fa747b9e4e049f71856c2eadccc6113f7ff2f7c
bigcode/the-stack
train
dbbf2b0803bab8f0ebbe4600
train
class
class TradeOrderTest(TradeOrderHandlerBase): """ order update push""" def on_recv_rsp(self, rsp_pb): ret, content = super(TradeOrderTest, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print("* TradeOrderTest content={}\n".format(content)) return ret, content
class TradeOrderTest(TradeOrderHandlerBase):
""" order update push""" def on_recv_rsp(self, rsp_pb): ret, content = super(TradeOrderTest, self).on_recv_rsp(rsp_pb) if ret == RET_OK: print("* TradeOrderTest content={}\n".format(content)) return ret, content
print("* SysNotify main_type='{}' sub_type='{}' msg='{}'\n".format(main_type, sub_type, msg)) else: print("* SysNotify error:{}\n".format(content)) return ret_code, content class TradeOrderTest(TradeOrderHandlerBase):
64
64
73
10
53
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
TradeOrderTest
TradeOrderTest
98
106
98
98
dac7e668555ee1f3aa7162020ea89e688b39a17d
bigcode/the-stack
train
ada502e678514c1b2dfc8f58
train
class
class RTDataTest(RTDataHandlerBase): """ 获取分时推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(RTDataTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* RTDataTest: error, msg: %s" % content) return RET_ERROR, cont...
class RTDataTest(RTDataHandlerBase):
""" 获取分时推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(RTDataTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* RTDataTest: error, msg: %s" % content) return RET_ERROR, content # print("* RTDataTest :%s...
ret_code, content = super(CurKlineTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* CurKlineTest: error, msg: %s" % content) return RET_OK, content class RTDataTest(RTDataHandlerBase):
64
64
113
10
53
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
RTDataTest
RTDataTest
34
43
34
34
8d696e217ce056d8519de9fc55700d8d260a81f7
bigcode/the-stack
train
5b354d26d4b8d3292ef6adf7
train
function
def quote_test(): ''' 行情接口调用测试 :return: ''' quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 设置异步回调接口 quote_ctx.set_handler(StockQuoteTest()) quote_ctx.set_handler(CurKlineTest()) quote_ctx.set_handler(RTDataTest()) quote_ctx.set_handler(TickerTest()) ...
def quote_test():
''' 行情接口调用测试 :return: ''' quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) # 设置异步回调接口 quote_ctx.set_handler(StockQuoteTest()) quote_ctx.set_handler(CurKlineTest()) quote_ctx.set_handler(RTDataTest()) quote_ctx.set_handler(TickerTest()) quote_ctx.set_hand...
def on_recv_rsp(self, rsp_pb): """receive response callback function""" ret_code, content = super(SysNotifyTest, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: main_type, sub_type, msg = content print("* SysNotify main_type='{}' sub_type='{}' msg='{}'\n".format(...
256
256
1,162
4
251
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
quote_test
quote_test
120
198
120
120
e6958752487fda64c3f92c1ee266efab973b4727
bigcode/the-stack
train
1832b605f7ce46180c37f1fd
train
class
class CurKlineTest(CurKlineHandlerBase): """ kline push""" def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(CurKlineTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* CurKlineTest: error, msg: %s" % content) return RET_OK, co...
class CurKlineTest(CurKlineHandlerBase):
""" kline push""" def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(CurKlineTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* CurKlineTest: error, msg: %s" % content) return RET_OK, content
ret_code != RET_OK: logger.debug("StockQuoteTest: error, msg: %s" % content) return RET_ERROR, content # print("* StockQuoteTest : %s" % content) return RET_OK, content class CurKlineTest(CurKlineHandlerBase):
64
64
91
12
51
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
CurKlineTest
CurKlineTest
24
31
24
24
3174812b81234042fbfb382247da5d24fe5eb35c
bigcode/the-stack
train
7496f4445e7fe09973714ce6
train
class
class BrokerTest(BrokerHandlerBase): """ 获取经纪队列推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, stock_code, contents = super(BrokerTest, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: bid_content = contents[0] ask_content = contents[1] ...
class BrokerTest(BrokerHandlerBase):
""" 获取经纪队列推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, stock_code, contents = super(BrokerTest, self).on_recv_rsp(rsp_pb) if ret_code == RET_OK: bid_content = contents[0] ask_content = contents[1] # print("* BrokerTest code \...
_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* OrderBookTest: error, msg: %s" % content) return RET_ERROR, content # print("* OrderBookTest\n", content) return RET_OK, content class BrokerTest(BrokerHandlerBase):
64
64
128
8
55
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
BrokerTest
BrokerTest
70
81
70
70
ab0d62260d43f0469ba9fb1215e517d9df6d1ec4
bigcode/the-stack
train
3ad71079a0ef3791d90e1b36
train
function
def trade_hkcc_test(): """ A股通交易测试 :return: """ trd_ctx = OpenHKCCTradeContext(host='127.0.0.1', port=11111) trd_ctx.set_handler(TradeOrderTest()) trd_ctx.set_handler(TradeDealTest()) trd_ctx.start() # 交易请求必须先解锁 !!! pwd_unlock = '979899' print("* unlock_trade : {...
def trade_hkcc_test():
""" A股通交易测试 :return: """ trd_ctx = OpenHKCCTradeContext(host='127.0.0.1', port=11111) trd_ctx.set_handler(TradeOrderTest()) trd_ctx.set_handler(TradeDealTest()) trd_ctx.start() # 交易请求必须先解锁 !!! pwd_unlock = '979899' print("* unlock_trade : {}\n".format(trd_ctx.unlo...
'))) # # print("* get_market_snapshot : {}\n".format(quote_ctx.get_market_snapshot('HK.21901'))) # print("* get_market_snapshot : {}\n".format(quote_ctx.get_market_snapshot(code_list))) # # print("* get_plate_list : {}\n".format(quote_ctx.get_plate_list(Market.HK, Plate.ALL))) # print("* g...
135
136
455
7
128
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
trade_hkcc_test
trade_hkcc_test
202
235
202
202
0ba7ef08097f990ee338c2a1c5bfa09defa05f7c
bigcode/the-stack
train
7e4c465e5981713f9f11f8eb
train
class
class TickerTest(TickerHandlerBase): """ 获取逐笔推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(TickerTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* TickerTest: error, msg: %s" % content) return RET_ERROR, cont...
class TickerTest(TickerHandlerBase):
""" 获取逐笔推送数据 """ def on_recv_rsp(self, rsp_pb): """数据响应回调函数""" ret_code, content = super(TickerTest, self).on_recv_rsp(rsp_pb) if ret_code != RET_OK: print("* TickerTest: error, msg: %s" % content) return RET_ERROR, content # print("* TickerTest\n",...
if ret_code != RET_OK: print("* RTDataTest: error, msg: %s" % content) return RET_ERROR, content # print("* RTDataTest :%s \n" % content) return RET_OK, content class TickerTest(TickerHandlerBase):
64
64
106
9
54
CatTiger/vnpy
venv/lib/python3.7/site-packages/futu/examples/check_all_get_push.py
Python
TickerTest
TickerTest
46
55
46
46
cc8c8af6e5f7c11ed217076f30444cdc21ff4ce3
bigcode/the-stack
train
2f0bd5eae098f111efbe034a
train
class
class TestV1beta2DeploymentList(unittest.TestCase): """V1beta2DeploymentList unit test stubs""" def setUp(self): pass def tearDown(self): pass def testV1beta2DeploymentList(self): """Test V1beta2DeploymentList""" # FIXME: construct object with mandatory attributes with...
class TestV1beta2DeploymentList(unittest.TestCase):
"""V1beta2DeploymentList unit test stubs""" def setUp(self): pass def tearDown(self): pass def testV1beta2DeploymentList(self): """Test V1beta2DeploymentList""" # FIXME: construct object with mandatory attributes with example values # model = kubernetes.client....
future__ import absolute_import import unittest import kubernetes.client from kubernetes.client.models.v1beta2_deployment_list import V1beta2DeploymentList # noqa: E501 from kubernetes.client.rest import ApiException class TestV1beta2DeploymentList(unittest.TestCase):
64
64
110
12
51
itholic/python
kubernetes/test/test_v1beta2_deployment_list.py
Python
TestV1beta2DeploymentList
TestV1beta2DeploymentList
22
35
22
22
0154b3ac88819f68270b4b196345a5df646cd6d6
bigcode/the-stack
train
c51d609ac06a8a07f0a966c4
train
class
class SimulationControllerServicer(object): """Feature: Simulation Controller This Feature provides control over the simulation behaviour of a SiLA Server. A SiLA Server can run in two modes: (a) a real mode - with real activities, e.g. addressing or controlling real hardware, writing to real databases, mov...
class SimulationControllerServicer(object):
"""Feature: Simulation Controller This Feature provides control over the simulation behaviour of a SiLA Server. A SiLA Server can run in two modes: (a) a real mode - with real activities, e.g. addressing or controlling real hardware, writing to real databases, moving real plates etc. (b) a simulation mode...
Mode_Responses.FromString, ) self.Get_SimulationMode = channel.unary_unary( '/sila2.org.silastandard.core.simulationcontroller.v1.SimulationController/Get_SimulationMode', request_serializer=SimulationController__pb2.Get_SimulationMode_Parameters.SerializeToString, response_deseriali...
92
92
309
7
85
lemmi25/sila2lib
sila_library/sila2lib/framework/std_features/SimulationController_pb2_grpc.py
Python
SimulationControllerServicer
SimulationControllerServicer
45
86
45
45
5cc19ee3a554fe7db0489cf660e5a565b2cdb49a
bigcode/the-stack
train
12b536f2c7e74d7c2e392e5f
train
class
class SimulationControllerStub(object): """Feature: Simulation Controller This Feature provides control over the simulation behaviour of a SiLA Server. A SiLA Server can run in two modes: (a) a real mode - with real activities, e.g. addressing or controlling real hardware, writing to real databases, moving ...
class SimulationControllerStub(object):
"""Feature: Simulation Controller This Feature provides control over the simulation behaviour of a SiLA Server. A SiLA Server can run in two modes: (a) a real mode - with real activities, e.g. addressing or controlling real hardware, writing to real databases, moving real plates etc. (b) a simulation mode...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import SimulationController_pb2 as SimulationController__pb2 class SimulationControllerStub(object):
38
111
370
6
31
lemmi25/sila2lib
sila_library/sila2lib/framework/std_features/SimulationController_pb2_grpc.py
Python
SimulationControllerStub
SimulationControllerStub
7
42
7
7
f773e239bdb15792b9c8bd7b17b1e702e23e4d3b
bigcode/the-stack
train
49383889b2441fdc9db4711a
train
function
def add_SimulationControllerServicer_to_server(servicer, server): rpc_method_handlers = { 'StartSimulationMode': grpc.unary_unary_rpc_method_handler( servicer.StartSimulationMode, request_deserializer=SimulationController__pb2.StartSimulationMode_Parameters.FromString, response_ser...
def add_SimulationControllerServicer_to_server(servicer, server):
rpc_method_handlers = { 'StartSimulationMode': grpc.unary_unary_rpc_method_handler( servicer.StartSimulationMode, request_deserializer=SimulationController__pb2.StartSimulationMode_Parameters.FromString, response_serializer=SimulationController__pb2.StartSimulationMode_Responses.Se...
imulationMode(self, request, context): """SimulationMode Indication whether SiLA Server is in Simulation Mode or not. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_SimulationControll...
74
75
250
14
61
lemmi25/sila2lib
sila_library/sila2lib/framework/std_features/SimulationController_pb2_grpc.py
Python
add_SimulationControllerServicer_to_server
add_SimulationControllerServicer_to_server
89
109
89
89
ae991c415eb95fb315413ac169d2d74fbcd43447
bigcode/the-stack
train
b202da3003f3b9c76464e2f7
train
class
class PrimitiveType(Enum): # TODO: categorical float = float int = int str = str bytes = bytes bool = bool datetime = datetime
class PrimitiveType(Enum): # TODO: categorical
float = float int = int str = str bytes = bytes bool = bool datetime = datetime
from datetime import datetime from enum import Enum from typing import Type import sqlalchemy as sa class PrimitiveType(Enum): # TODO: categorical
31
64
41
11
19
papsebestyen/sscutils
sscutils/primitive_types.py
Python
PrimitiveType
PrimitiveType
8
15
8
9
1b3e87a69e3a0b1a332cf7c2841ba0a1b1a4f822
bigcode/the-stack
train
dafca62c25600acf400e8446
train
function
def get_sa_type(dtype: Type): return sa_type_map[dtype]
def get_sa_type(dtype: Type):
return sa_type_map[dtype]
from enum import Enum from typing import Type import sqlalchemy as sa class PrimitiveType(Enum): # TODO: categorical float = float int = int str = str bytes = bytes bool = bool datetime = datetime def get_sa_type(dtype: Type):
64
64
16
8
55
papsebestyen/sscutils
sscutils/primitive_types.py
Python
get_sa_type
get_sa_type
18
19
18
18
e21941840542ca7184afef1c9f51c98d271364f5
bigcode/the-stack
train
30199334993feaa0c912cfc4
train
function
def get_np_type(dtype: Type): return {datetime: "datetime64", str: object}.get(dtype, dtype)
def get_np_type(dtype: Type):
return {datetime: "datetime64", str: object}.get(dtype, dtype)
PrimitiveType(Enum): # TODO: categorical float = float int = int str = str bytes = bytes bool = bool datetime = datetime def get_sa_type(dtype: Type): return sa_type_map[dtype] def get_np_type(dtype: Type):
64
64
26
8
56
papsebestyen/sscutils
sscutils/primitive_types.py
Python
get_np_type
get_np_type
22
23
22
22
8f5d359b77ebd9f38ddfd591d1bb5e2c6869b80f
bigcode/the-stack
train
ee7e237ab35acbd0a6704211
train
class
class TestSequenceFunctions(unittest.TestCase): def test_resolve(self): ret = resolve('viagra') self.assertEqual(len(ret), 1) self.assertEqual(ret[0]['molecule_chembl_id'], 'CHEMBL1737') ret = resolve('gleevec') self.assertEqual(len(ret), 2) self.assertEqual(ret[0]...
class TestSequenceFunctions(unittest.TestCase):
def test_resolve(self): ret = resolve('viagra') self.assertEqual(len(ret), 1) self.assertEqual(ret[0]['molecule_chembl_id'], 'CHEMBL1737') ret = resolve('gleevec') self.assertEqual(len(ret), 2) self.assertEqual(ret[0]['molecule_chembl_id'], 'CHEMBL941') self...
0 17 15 1 0 18 11 1 0 19 11 1 0 20 17 1 0 21 7 2 0 22 13 2 0 23 8 1 0 24 10 1 0 25 13 1 0 27 16 1 0 28 20 1 0 29 23 1 0 30 27 1 0 17 31 1 6 16 32 1 6 19 18 1 0 7 4 1 0 10 12 2 0 17 16 1 0 28 30 1 0 M END > <chembl_id> CHEMBL1200735 $$$$ ''' class Test...
256
256
6,293
8
248
RowAnalytics/chembl_webresource_client
chembl_webresource_client/test_utils.py
Python
TestSequenceFunctions
TestSequenceFunctions
173
510
173
174
17381664ddcd6a85469a06762eec75de91a41352
bigcode/the-stack
train
f14c9ab3cad601e5c387ba7a
train
function
def u(c): return (np.float_power(c, 1-gamma) - 1)/(1 - gamma)
def u(c):
return (np.float_power(c, 1-gamma) - 1)/(1 - gamma)
from scipy.interpolate import interpn from multiprocessing import Pool from functools import partial from constant import * import warnings warnings.filterwarnings("ignore") #Define the utility function def u(c):
40
64
25
4
35
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
u
u
9
10
9
9
0fdbd46357c56b59730260d0579882b4748cc2a3
bigcode/the-stack
train
57d32ae32a196ee507a8b908
train
function
def uB(tb): return B*u(tb)
def uB(tb):
return B*u(tb)
from constant import * import warnings warnings.filterwarnings("ignore") #Define the utility function def u(c): return (np.float_power(c, 1-gamma) - 1)/(1 - gamma) #Define the bequeath function, which is a function of wealth def uB(tb):
64
64
11
5
58
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
uB
uB
13
14
13
13
927c59e1ef38837ea1899de075a3f72a17060fab
bigcode/the-stack
train
b08c368722c79e41c956ceb0
train
function
def calTB(x): # the input x as a numpy array # w, n, M, e, s, z = x TB = x[:,0] + x[:,1] + calHE(x) return TB
def calTB(x): # the input x as a numpy array # w, n, M, e, s, z = x
TB = x[:,0] + x[:,1] + calHE(x) return TB
w, n, M, e, s, z = x HE = H*pt - x[:,2] return HE #Calculate TB def calTB(x): # the input x as a numpy array # w, n, M, e, s, z = x
64
64
52
31
32
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
calTB
calTB
24
28
24
26
4b5aaf4fbed1738228efdca62b21fdaf137d1fb1
bigcode/the-stack
train
c6793956e5e49aed0a185ba7
train
function
def transition(x, a, t): ''' Input: state and action and time, where action is an array Output: possible future states and corresponding probability ''' w, n, M, e, s, z = x s = int(s) e = int(e) aSize = len(a) nX = len(x) # mortgage payment m = M/D[T_max-t] M_ne...
def transition(x, a, t):
''' Input: state and action and time, where action is an array Output: possible future states and corresponding probability ''' w, n, M, e, s, z = x s = int(s) e = int(e) aSize = len(a) nX = len(x) # mortgage payment m = M/D[T_max-t] M_next = M*(1+rh) - m # a...
out nrent_index = (a[:,3]==1) # actions with renting out rent_index = (a[:,3]!=1) # housing consumption not renting out nrent_Vh = (1+kappa)*H # housing consumption renting out rent_Vh = (1-kappa)*H*a[:,3] # combined consumption with housing consumption nrent_C = np.float_power...
180
180
601
8
171
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
transition
transition
57
105
57
57
9e6e2bcb8979b99989280263b568f56a64031a73
bigcode/the-stack
train
734f42270df3af84abc82656
train
function
def R(x, a): ''' Input: state x: w, n, M, e, s, z action a: c, b, k, q = a which is a np array Output: reward value: the length of return should be equal to the length of a ''' w, n, M, e, s, z = x reward = np.zeros(a.shape[0]) # actions with not renting out nre...
def R(x, a):
''' Input: state x: w, n, M, e, s, z action a: c, b, k, q = a which is a np array Output: reward value: the length of return should be equal to the length of a ''' w, n, M, e, s, z = x reward = np.zeros(a.shape[0]) # actions with not renting out nrent_index = (a...
HE = H*pt - x[:,2] return HE #Calculate TB def calTB(x): # the input x as a numpy array # w, n, M, e, s, z = x TB = x[:,0] + x[:,1] + calHE(x) return TB #The reward function def R(x, a):
81
81
272
6
74
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
R
R
31
54
31
31
b118cf18b2bcebc7c0f6df197705c9111ecd946b
bigcode/the-stack
train
c94849a05b65e8d0a6e10187
train
function
def calHE(x): # the input x is a numpy array # w, n, M, e, s, z = x HE = H*pt - x[:,2] return HE
def calHE(x): # the input x is a numpy array # w, n, M, e, s, z = x
HE = H*pt - x[:,2] return HE
) #Define the bequeath function, which is a function of wealth def uB(tb): return B*u(tb) #Calcualte HE def calHE(x): # the input x is a numpy array # w, n, M, e, s, z = x
64
64
46
31
32
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
calHE
calHE
17
21
17
19
4cff51a6449c025c2a4388e03f4c33870d0f538f
bigcode/the-stack
train
45e77e8d1b9b1881086b6769
train
function
def V(x, t, NN): w, n, M, e, s, z = x yat = yAT(t,x) m = M/D[T_max - t] # If the agent can not pay for the ortgage if yat + w < m: return [0, [0,0,0,0,0]] # The agent can pay for the mortgage if t == T_max-1: # The objective functions of terminal state def obj(actio...
def V(x, t, NN):
w, n, M, e, s, z = x yat = yAT(t,x) m = M/D[T_max - t] # If the agent can not pay for the ortgage if yat + w < m: return [0, [0,0,0,0,0]] # The agent can pay for the mortgage if t == T_max-1: # The objective functions of terminal state def obj(actions): ...
class Approxy(object): def __init__(self, points, Vgrid): self.V = Vgrid self.p = points def predict(self, xx): pvalues = np.zeros(xx.shape[0]) for e in [0,1]: for s in range(nS): for z in [0,1]: index = (xx[:,3] == e) & (xx[:,4] ...
256
256
958
8
247
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
V
V
131
226
131
131
db64fba0be0e177d9e0ed830d328907480871ab7
bigcode/the-stack
train
f91346484363eaa6e47073c9
train
class
class Approxy(object): def __init__(self, points, Vgrid): self.V = Vgrid self.p = points def predict(self, xx): pvalues = np.zeros(xx.shape[0]) for e in [0,1]: for s in range(nS): for z in [0,1]: index = (xx[:,3] == e) & (xx[:,4] =...
class Approxy(object):
def __init__(self, points, Vgrid): self.V = Vgrid self.p = points def predict(self, xx): pvalues = np.zeros(xx.shape[0]) for e in [0,1]: for s in range(nS): for z in [0,1]: index = (xx[:,3] == e) & (xx[:,4] == s) & (xx[:,5] == z) ...
]*(1-Pe[s,e])),aSize) else: future_probs = np.tile(np.append(Ps[s]*(1-Pe[s,e]), Ps[s]*Pe[s,e]),aSize) return future_states, future_probs # Use to approximate the discrete values in V class Approxy(object):
64
64
145
5
58
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
Approxy
Approxy
109
121
109
109
3f2309b71d64485de8be6dde7051e8464fc434f8
bigcode/the-stack
train
6317dc902f67a85dd9ecc185
train
function
def dotProduct(p_next, uBTB, t): if t >= 45: return (p_next*uBTB).reshape((len(p_next)//(nS),(nS))).sum(axis = 1) else: return (p_next*uBTB).reshape((len(p_next)//(2*nS),(2*nS))).sum(axis = 1)
def dotProduct(p_next, uBTB, t):
if t >= 45: return (p_next*uBTB).reshape((len(p_next)//(nS),(nS))).sum(axis = 1) else: return (p_next*uBTB).reshape((len(p_next)//(2*nS),(2*nS))).sum(axis = 1)
== z) pvalues[index]=interpn(self.p, self.V[:,:,:,e,s,z], xx[index][:,:3], bounds_error = False, fill_value = None) return pvalues # used to calculate dot product def dotProduct(p_next, uBTB, t):
64
64
80
12
51
dongxulee/lifeCycle
20201120/20201116/.ipynb_checkpoints/solveHousing-checkpoint.py
Python
dotProduct
dotProduct
124
128
124
124
d5e64bbd613e61a47fc9cddc77c103424daaed07
bigcode/the-stack
train
fd6f7634310c2fdb82a9f75f
train
class
class KindManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug)
class KindManager(models.Manager):
def get_by_natural_key(self, slug): return self.get(slug=slug)
from django.db import models class KindManager(models.Manager):
13
64
27
7
5
jtauber/team566
manoria_project/apps/manoria/managers.py
Python
KindManager
KindManager
4
7
4
5
28c230680859137a3b075367d21ba43bc407b24a
bigcode/the-stack
train
d424a083dfd450134e503e62
train
function
def detect(sess, rcnn_cls, image): # pre-processing image for Faster-RCNN img_origin = image.astype(np.float32, copy=True) img_origin -= np.array([[[102.9801, 115.9465, 112.7717]]]) img_shape = img_origin.shape img_size_min = np.min(img_shape[:2]) img_size_max = np.max(img_shape[:2]) img_s...
def detect(sess, rcnn_cls, image): # pre-processing image for Faster-RCNN
img_origin = image.astype(np.float32, copy=True) img_origin -= np.array([[[102.9801, 115.9465, 112.7717]]]) img_shape = img_origin.shape img_size_min = np.min(img_shape[:2]) img_size_max = np.max(img_shape[:2]) img_scale = 600 / img_size_min if np.round(img_scale * img_size_max) > 1000: ...
import os from pathlib import Path import numpy as np import cv2 from faster_rcnn_wrapper import FasterRCNNSlim from _tf_compat_import import compat_tensorflow as tf import argparse from nms_wrapper import NMSType, NMSWrapper def detect(sess, rcnn_cls, image): # pre-processing image for Faster-RCNN
77
196
656
20
56
shalebark/anime-face-detector
api.py
Python
detect
detect
11
56
11
12
037f4755a86ae790b9de8e13e6a3df65e92e2269
bigcode/the-stack
train
b33be222bee0b0081698b4e1
train
class
class FaceDetector(): def __init__(self, model_path=None, nms_type='CPU_NMS', nms_threshold=0.3, threshold=0.8): """ Parameters: nms_type: Type of NMS. Options ("PY_NMS" | "CPU_NMS" | "GPU_NMS") nms_threshold: Threshold for Non Max Suppression. (float) threshold:...
class FaceDetector():
def __init__(self, model_path=None, nms_type='CPU_NMS', nms_threshold=0.3, threshold=0.8): """ Parameters: nms_type: Type of NMS. Options ("PY_NMS" | "CPU_NMS" | "GPU_NMS") nms_threshold: Threshold for Non Max Suppression. (float) threshold: Threshold for class r...
_y - 0.5 * pred_h pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h # clipping edge pred_boxes[:, 0::4] = np.maximum(pred_boxes[:, 0::4], 0) pred_boxes[:, 1::4] = np.maximum(pred_boxes[:, 1::4], 0) pred_boxes[:, 2::4] = np.minimum(pred_boxes[:, 2::4]...
174
174
583
4
169
shalebark/anime-face-detector
api.py
Python
FaceDetector
FaceDetector
58
120
58
58
bb0b8654739a797e74920f4f7d676f0259f1d13d
bigcode/the-stack
train
bf47119e0af2d5f6ee1c247d
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,...
class Migration(migrations.Migration):
initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 3.1.2 on 2021-01-17 16:42 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import kronikarz.api.models class Migration(migrations.Migratio...
76
256
1,314
7
68
KronikarzIO/Kronikarz
kronikarz/api/migrations/0001_initial.py
Python
Migration
Migration
12
106
12
13
882ded67565217f711d6c3c5ec9d5613983b29eb
bigcode/the-stack
train
8f8630876aa54427fd43edc7
train
function
def typify_function(name, argtypes, globls, node): typify = Typify(name, argtypes, globls) func_ast = typify.make_cfunction(node) make_kernel(func_ast) return typify.make_module(func_ast), func_ast
def typify_function(name, argtypes, globls, node):
typify = Typify(name, argtypes, globls) func_ast = typify.make_cfunction(node) make_kernel(func_ast) return typify.make_module(func_ast), func_ast
_def): returns = return_nodes(cfunc_def.body) for return_node in returns: return_node.value = None cfunc_def.decorator_list.insert(0, cast.clkernel()) cfunc_def.return_type = None def typify_function(name, argtypes, globls, node):
64
64
57
14
49
srossross/Clyther
clyther/pipeline.py
Python
typify_function
typify_function
35
39
35
35
25db49fd93ad8e3d0739104d00f8ff334c08b1b7
bigcode/the-stack
train
806a48a735cd57871757c3f7
train
function
def create_kernel_source(function, argtypes): ''' Create OpenCL source code from a Python function. :param function: A pure python function :param argtypes: A dict of name:type for the compiler to use in optimizing the function. Steps: * Decompile to AST.: Get ...
def create_kernel_source(function, argtypes):
''' Create OpenCL source code from a Python function. :param function: A pure python function :param argtypes: A dict of name:type for the compiler to use in optimizing the function. Steps: * Decompile to AST.: Get AST from python bytecode * Typify AST:...
lyther.clast.visitors.returns import return_nodes from clyther.clast.visitors.typify import Typify from clyther.rttt import replace_types from meta.decompiler import decompile_func from clyther.clast.mutators.replace_constants import replace_constants def make_kernel(cfunc_def): returns = return_nodes(cfunc_def...
182
182
609
9
172
srossross/Clyther
clyther/pipeline.py
Python
create_kernel_source
create_kernel_source
42
113
42
42
48997f607654ef31270031892d4e82ae9785acf5
bigcode/the-stack
train
f4082f0e4f771a4ebfb3946c
train
function
def make_kernel(cfunc_def): returns = return_nodes(cfunc_def.body) for return_node in returns: return_node.value = None cfunc_def.decorator_list.insert(0, cast.clkernel()) cfunc_def.return_type = None
def make_kernel(cfunc_def):
returns = return_nodes(cfunc_def.body) for return_node in returns: return_node.value = None cfunc_def.decorator_list.insert(0, cast.clkernel()) cfunc_def.return_type = None
.visitors.returns import return_nodes from clyther.clast.visitors.typify import Typify from clyther.rttt import replace_types from meta.decompiler import decompile_func from clyther.clast.mutators.replace_constants import replace_constants def make_kernel(cfunc_def):
64
64
55
7
56
srossross/Clyther
clyther/pipeline.py
Python
make_kernel
make_kernel
26
32
26
26
c9cff999a26525099e2a0ad379cd4a3619a00955
bigcode/the-stack
train
8c04160e23ca710f60889c7e
train
function
def deprecated(old): def new(*args, **kwargs): print('Function %s is deprecated.' % old.__name__, file=sys.stderr) trace = traceback.extract_stack() for line in traceback.format_list(trace[:-1]): stderr(line[:-1]) return old(*args, **kwargs) new.__doc__ = old.__doc__ ...
def deprecated(old):
def new(*args, **kwargs): print('Function %s is deprecated.' % old.__name__, file=sys.stderr) trace = traceback.extract_stack() for line in traceback.format_list(trace[:-1]): stderr(line[:-1]) return old(*args, **kwargs) new.__doc__ = old.__doc__ new.__name__ = ol...
# Group 2 must be None, if there are no # parameters. $ # EoL, so there are no partial matches. """.format(prefix=prefix, command=command) return re.compile(pattern, re.IGNORECASE | re.VERBOSE) def deprecated(old):
64
64
88
4
60
mclellac/connery
connery/tools/__init__.py
Python
deprecated
deprecated
94
103
94
94
ddddd5b2de75228def742dca3e77eea5e1ebeb94
bigcode/the-stack
train
d52ebed3d4821726eb097392
train
function
def stderr(string): """Print the given ``string`` to stderr. This is equivalent to ``print >> sys.stderr, string`` """ print(string, file=sys.stderr)
def stderr(string):
"""Print the given ``string`` to stderr. This is equivalent to ``print >> sys.stderr, string`` """ print(string, file=sys.stderr)
was why we were having problems. We'll drop it in # 4.0^H^H^H5.0^H^H^H6.0^H^H^Hsome version when someone can be bothered. @deprecated def stdout(string): print(string) def stderr(string):
64
64
39
4
60
mclellac/connery
connery/tools/__init__.py
Python
stderr
stderr
259
265
259
259
88c0a623821fac65be44d2099d33c4d9d5bf6d86
bigcode/the-stack
train
2fd83b683a613f08aff7098e
train
function
@deprecated def stdout(string): print(string)
@deprecated def stdout(string):
print(string)
prints, # because it looked like that was why we were having problems. We'll drop it in # 4.0^H^H^H5.0^H^H^H6.0^H^H^Hsome version when someone can be bothered. @deprecated def stdout(string):
64
64
11
7
57
mclellac/connery
connery/tools/__init__.py
Python
stdout
stdout
254
256
254
255
f552197e7ca62d2406c136d5388c2f28bbc92921
bigcode/the-stack
train
06f6db84c089af1482a2a05d
train
function
def check_pid(pid): """Check if a process is running with the given ``PID``. *Availability: Only on POSIX systems* Return ``True`` if there is a process running with the given ``PID``. """ try: os.kill(pid, 0) except OSError: return False else: return True
def check_pid(pid):
"""Check if a process is running with the given ``PID``. *Availability: Only on POSIX systems* Return ``True`` if there is a process running with the given ``PID``. """ try: os.kill(pid, 0) except OSError: return False else: return True
Hsome version when someone can be bothered. @deprecated def stdout(string): print(string) def stderr(string): """Print the given ``string`` to stderr. This is equivalent to ``print >> sys.stderr, string`` """ print(string, file=sys.stderr) def check_pid(pid):
64
64
75
5
59
mclellac/connery
connery/tools/__init__.py
Python
check_pid
check_pid
268
281
268
268
ba68aafa53c481a3e8c62c39fa08638c18433044
bigcode/the-stack
train
aea9662a418c9e4a50de7fef
train
class
class Identifier(unicode): """A `unicode` subclass which acts appropriately for IRC identifiers. When used as normal `unicode` objects, case will be preserved. However, when comparing two Identifier objects, or comparing a Identifier object with a `unicode` object, the comparison will be case insensiti...
class Identifier(unicode):
"""A `unicode` subclass which acts appropriately for IRC identifiers. When used as normal `unicode` objects, case will be preserved. However, when comparing two Identifier objects, or comparing a Identifier object with a `unicode` object, the comparison will be case insensitive. This case insensiti...
) trace = traceback.extract_stack() for line in traceback.format_list(trace[:-1]): stderr(line[:-1]) return old(*args, **kwargs) new.__doc__ = old.__doc__ new.__name__ = old.__name__ return new # from # http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional...
190
190
635
5
185
mclellac/connery
connery/tools/__init__.py
Python
Identifier
Identifier
126
199
126
126
9f8cac7e55cb4a287deccc7f5bef6b2f806922f5
bigcode/the-stack
train
c344692f7a02643045f2b648
train
class
class Ddict(dict): """Class for multi-dimensional ``dict``. A simple helper class to ease the creation of multi-dimensional ``dict``\s. """ def __init__(self, default=None): self.default = default def __getitem__(self, key): if key not in self: self[key] = self.defau...
class Ddict(dict):
"""Class for multi-dimensional ``dict``. A simple helper class to ease the creation of multi-dimensional ``dict``\s. """ def __init__(self, default=None): self.default = default def __getitem__(self, key): if key not in self: self[key] = self.default() return ...
doc__ new.__name__ = old.__name__ return new # from # http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/ # A simple class to make mutli dimensional dict easy to use class Ddict(dict):
64
64
84
5
58
mclellac/connery
connery/tools/__init__.py
Python
Ddict
Ddict
109
123
109
110
07a956084bc097b74966a5d032b74b6282da9595
bigcode/the-stack
train
4f721df618f08f17c5000c1a
train
function
def get_raising_file_and_line(tb=None): """Return the file and line number of the statement that raised the tb. Returns: (filename, lineno) tuple """ if not tb: tb = sys.exc_info()[2] filename, lineno, _context, _line = traceback.extract_tb(tb)[-1] return filename, lineno
def get_raising_file_and_line(tb=None):
"""Return the file and line number of the statement that raised the tb. Returns: (filename, lineno) tuple """ if not tb: tb = sys.exc_info()[2] filename, lineno, _context, _line = traceback.extract_tb(tb)[-1] return filename, lineno
# NOQA ExpressionEvaluator, guarded_mul, pow_complexity, guarded_pow, EquationEvaluator, eval_equation ) from .time import get_timezone, format_time # NOQA from .jobs import PriorityQueue, released # NOQA def get_raising_file_and_line(tb=None):
64
64
80
10
53
mclellac/connery
connery/tools/__init__.py
Python
get_raising_file_and_line
get_raising_file_and_line
51
62
51
51
16a2a9c1dbf7c03c580b80f97530caa101e78e50
bigcode/the-stack
train
3b63ac6473b5cc4f5e21eb95
train
function
def get_hostmask_regex(mask): """Return a compiled `re.RegexObject` for an IRC hostmask""" mask = re.escape(mask) mask = mask.replace(r'\*', '.*') return re.compile(mask + '$', re.I)
def get_hostmask_regex(mask):
"""Return a compiled `re.RegexObject` for an IRC hostmask""" mask = re.escape(mask) mask = mask.replace(r'\*', '.*') return re.compile(mask + '$', re.I)
``. *Availability: Only on POSIX systems* Return ``True`` if there is a process running with the given ``PID``. """ try: os.kill(pid, 0) except OSError: return False else: return True def get_hostmask_regex(mask):
64
64
53
7
56
mclellac/connery
connery/tools/__init__.py
Python
get_hostmask_regex
get_hostmask_regex
284
288
284
284
353ee4690af7e5a5fb6c01ad0ef8eb72d0d6fd36
bigcode/the-stack
train
fb4a254a90bb73664f65301b
train
class
class OutputRedirect(object): """Redirect te output to the terminal and a log file. A simplified object used to write to both the terminal and a log file. """ def __init__(self, logpath, stderr=False, quiet=False): """Create an object which will to to a file and the terminal. Create...
class OutputRedirect(object):
"""Redirect te output to the terminal and a log file. A simplified object used to write to both the terminal and a log file. """ def __init__(self, logpath, stderr=False, quiet=False): """Create an object which will to to a file and the terminal. Create an object which will log to th...
eq__(self, other): if isinstance(other, Identifier): return self._lowered == other._lowered return self._lowered == Identifier._lower(other) def __ne__(self, other): return not (self == other) def is_nick(self): """Returns True if the Identifier is a nickname (as op...
96
96
321
5
91
mclellac/connery
connery/tools/__init__.py
Python
OutputRedirect
OutputRedirect
202
248
202
203
2ca93ebe64fffbbea325048332c97b179ccec2f5
bigcode/the-stack
train
d7a7b4b9eadd63796c5db973
train
function
def get_command_regexp(prefix, command): """Return a compiled regexp object that implements the command.""" # Escape all whitespace with a single backslash. This ensures that regexp # in the prefix is treated as it was before the actual regexp was changed # to use the verbose syntax. prefix = re.sub...
def get_command_regexp(prefix, command):
"""Return a compiled regexp object that implements the command.""" # Escape all whitespace with a single backslash. This ensures that regexp # in the prefix is treated as it was before the actual regexp was changed # to use the verbose syntax. prefix = re.sub(r"(\s)", r"\\\1", prefix) # This re...
jobs import PriorityQueue, released # NOQA def get_raising_file_and_line(tb=None): """Return the file and line number of the statement that raised the tb. Returns: (filename, lineno) tuple """ if not tb: tb = sys.exc_info()[2] filename, lineno, _context, _line = traceback.extract_tb(tb...
100
100
336
9
90
mclellac/connery
connery/tools/__init__.py
Python
get_command_regexp
get_command_regexp
65
91
65
65
654801b43788384ec75d5ba9f3f8063e04f7a537
bigcode/the-stack
train
dd1c447a6334061ea2f849e2
train
class
class ConneryMemory(dict): """A simple thread-safe dict implementation. *Availability: 4.0; available as ``Connery.ConneryMemory`` in 3.1.0 - 3.2.0* In order to prevent exceptions when iterating over the values and changing them at the same time from different threads, we use a blocking lock on `...
class ConneryMemory(dict):
"""A simple thread-safe dict implementation. *Availability: 4.0; available as ``Connery.ConneryMemory`` in 3.1.0 - 3.2.0* In order to prevent exceptions when iterating over the values and changing them at the same time from different threads, we use a blocking lock on ``__setitem__`` and ``contain...
(pid, 0) except OSError: return False else: return True def get_hostmask_regex(mask): """Return a compiled `re.RegexObject` for an IRC hostmask""" mask = re.escape(mask) mask = mask.replace(r'\*', '.*') return re.compile(mask + '$', re.I) class ConneryMemory(dict):
80
80
268
6
74
mclellac/connery
connery/tools/__init__.py
Python
ConneryMemory
ConneryMemory
291
329
291
292
50cf0b0b32d66f323c3ce1ca806725c550775ce3
bigcode/the-stack
train
01afbdea302937aa95306999
train
class
class ConneryMemoryWithDefault(defaultdict): """Same as ConneryMemory, but subclasses from collections.defaultdict.""" def __init__(self, *args): defaultdict.__init__(self, *args) self.lock = threading.Lock() def __setitem__(self, key, value): self.lock.acquire() result = de...
class ConneryMemoryWithDefault(defaultdict):
"""Same as ConneryMemory, but subclasses from collections.defaultdict.""" def __init__(self, *args): defaultdict.__init__(self, *args) self.lock = threading.Lock() def __setitem__(self, key, value): self.lock.acquire() result = defaultdict.__setitem__(self, key, value) ...
.lock.release() return result def contains(self, key): """Backwards compatability with 3.x, use `in` operator instead.""" return self.__contains__(key) def unlock(self): """Release the write lock.""" return self.lock.release() class ConneryMemoryWithDefault(defaultdict)...
67
67
225
9
58
mclellac/connery
connery/tools/__init__.py
Python
ConneryMemoryWithDefault
ConneryMemoryWithDefault
332
365
332
332
0aec2bfe8909d7468c24c02fa1f72faed23810f8
bigcode/the-stack
train
6068dafa85a70f2e43b61b08
train
function
def test_small_output_fails(rbf_node, dest_address): # cannot bump fee with a too-small output rbfid = spend_one_input(rbf_node, dest_address) rbf_node.bumpfee(rbfid, {"totalFee": 5000000}) rbfid = spend_one_input(rbf_node, dest_address) assert_raises_jsonrpc(-4, "Change output is too small", rbf_n...
def test_small_output_fails(rbf_node, dest_address): # cannot bump fee with a too-small output
rbfid = spend_one_input(rbf_node, dest_address) rbf_node.bumpfee(rbfid, {"totalFee": 5000000}) rbfid = spend_one_input(rbf_node, dest_address) assert_raises_jsonrpc(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 5000001})
txid = rbf_node.sendrawtransaction(tx["hex"]) assert_raises_jsonrpc(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id) def test_small_output_fails(rbf_node, dest_address): # cannot bump fee with a too-small output
64
64
108
24
40
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_small_output_fails
test_small_output_fails
175
181
175
176
63975d5de535707ad02b77dbd0e7fb6bb00a9f38
bigcode/the-stack
train
92176129c978323412732358
train
function
def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address): # cannot bump fee unless the tx has only inputs that we own. # here, the rbftx has a peer_node coin and then adds a rbf_node input # Note that this test depends upon the RPC code checking input ownership prior to change outputs # (since ...
def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address): # cannot bump fee unless the tx has only inputs that we own. # here, the rbftx has a peer_node coin and then adds a rbf_node input # Note that this test depends upon the RPC code checking input ownership prior to change outputs # (since ...
utxos = [node.listunspent()[-1] for node in (rbf_node, peer_node)] inputs = [{ "txid": utxo["txid"], "vout": utxo["vout"], "address": utxo["address"], "sequence": BIP125_SEQUENCE_NUMBER } for utxo in utxos] output_val = sum(utxo["amount"] for utxo in utxos) - Decimal("0.1...
def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address): # cannot bump fee unless the tx has only inputs that we own. # here, the rbftx has a peer_node coin and then adds a rbf_node input # Note that this test depends upon the RPC code checking input ownership prior to change outputs # (since ...
93
88
295
93
0
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_notmine_bumpfee_fails
test_notmine_bumpfee_fails
144
162
144
148
44389cd0450432c8a5d8576542ef437760b65d60
bigcode/the-stack
train
6fabb287be5f24ff4075302e
train
function
def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address): # cannot bump fee if the transaction has a descendant # parent is send-to-self, so we don't have to check which output is change when creating the child tx parent_id = spend_one_input(rbf_node, rbf_node_address) tx = rbf_n...
def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address): # cannot bump fee if the transaction has a descendant # parent is send-to-self, so we don't have to check which output is change when creating the child tx
parent_id = spend_one_input(rbf_node, rbf_node_address) tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.020000}) tx = rbf_node.signrawtransaction(tx) txid = rbf_node.sendrawtransaction(tx["hex"]) assert_raises_jsonrpc(-8, "Transaction has descendants in the wall...
fee, rbfid) def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address): # cannot bump fee if the transaction has a descendant # parent is send-to-self, so we don't have to check which output is change when creating the child tx
64
64
160
58
6
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_bumpfee_with_descendant_fails
test_bumpfee_with_descendant_fails
165
172
165
167
4a613135d26591b7075f7b4ee54604d446771f2f
bigcode/the-stack
train
8cdc9aa6f3e4399f0aa7de1e
train
class
class BumpFeeTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = True def setup_network(self, split=False): extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)] ...
class BumpFeeTest(BitcoinTestFramework):
def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = True def setup_network(self, split=False): extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)] for i in range(self.num_nodes)] s...
test cases implemented in the top-level functions named as test_<test_case_description>. The test functions can be disabled or reordered if needed for debugging. If new test cases are added in the future, they should try to follow the same convention and not make assumptions about execution order. """ from segwit imp...
172
172
576
10
161
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
BumpFeeTest
BumpFeeTest
32
82
32
32
c2795be109476ec84442c8c6a5cc1bedc5bd42ce
bigcode/the-stack
train
56be48dccee58f9724fa71f8
train
function
def test_bumpfee_metadata(rbf_node, dest_address): rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.100000"), "comment value", "to value") bumped_tx = rbf_node.bumpfee(rbfid) bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"]) assert_equal(bumped_wtx["comment"], "comment value") assert_eq...
def test_bumpfee_metadata(rbf_node, dest_address):
rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.100000"), "comment value", "to value") bumped_tx = rbf_node.bumpfee(rbfid) bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"]) assert_equal(bumped_wtx["comment"], "comment value") assert_equal(bumped_wtx["to"], "to value")
1 for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == rbfid and t["address"] == rbf_node_address and t["spendable"]), 1) def test_bumpfee_metadata(rbf_node, dest_address):
64
64
100
13
51
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_bumpfee_metadata
test_bumpfee_metadata
261
266
261
261
2f3b0c4e8f8f744aff2fe087d4ffffa9c2409082
bigcode/the-stack
train
2de0c0cd8233db001c4783bc
train
function
def test_nonrbf_bumpfee_fails(peer_node, dest_address): # cannot replace a non RBF transaction (from node which did not enable RBF) not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.090000")) assert_raises_jsonrpc(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
def test_nonrbf_bumpfee_fails(peer_node, dest_address): # cannot replace a non RBF transaction (from node which did not enable RBF)
not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.090000")) assert_raises_jsonrpc(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
txid"] in rbf_node.getrawmempool() assert rbfid not in rbf_node.getrawmempool() def test_nonrbf_bumpfee_fails(peer_node, dest_address): # cannot replace a non RBF transaction (from node which did not enable RBF)
64
64
84
35
29
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_nonrbf_bumpfee_fails
test_nonrbf_bumpfee_fails
138
141
138
139
27312683b74b406aa044e76af896487580e4250d
bigcode/the-stack
train
e33bc5872f335e3c5df558c8
train
function
def submit_block_with_tx(node, tx): ctx = CTransaction() ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx))) tip = node.getbestblockhash() height = node.getblockcount() + 1 block_time = node.getblockheader(tip)["mediantime"] + 1 block = blocktools.create_block(int(tip, 16), blocktools.create_coin...
def submit_block_with_tx(node, tx):
ctx = CTransaction() ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx))) tip = node.getbestblockhash() height = node.getblockcount() + 1 block_time = node.getblockheader(tip)["mediantime"] + 1 block = blocktools.create_block(int(tip, 16), blocktools.create_coinbase(height), block_time) block....
dest_address: Decimal("0.050000"), node.getrawchangeaddress(): Decimal("0.049000")}) signedtx = node.signrawtransaction(rawtx) txid = node.sendrawtransaction(signedtx["hex"]) return txid def submit_block_with_tx(node, tx):
64
64
136
9
54
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
submit_block_with_tx
submit_block_with_tx
287
300
287
287
db3a54c6746da68779f52670eb5463285754ee08
bigcode/the-stack
train
5221b3fad8142b1e56582ed5
train
function
def test_settxfee(rbf_node, dest_address): # check that bumpfee reacts correctly to the use of settxfee (paytxfee) rbfid = spend_one_input(rbf_node, dest_address) requested_feerate = Decimal("0.025000") rbf_node.settxfee(requested_feerate) bumped_tx = rbf_node.bumpfee(rbfid) actual_feerate = bum...
def test_settxfee(rbf_node, dest_address): # check that bumpfee reacts correctly to the use of settxfee (paytxfee)
rbfid = spend_one_input(rbf_node, dest_address) requested_feerate = Decimal("0.025000") rbf_node.settxfee(requested_feerate) bumped_tx = rbf_node.bumpfee(rbfid) actual_feerate = bumped_tx["fee"] * 1000 / rbf_node.getrawtransaction(bumped_tx["txid"], True)["size"] # Assert that the difference bet...
(len(fulltx["vout"]), 2) assert_equal(len(full_bumped_tx["vout"]), 1) #change output is eliminated def test_settxfee(rbf_node, dest_address): # check that bumpfee reacts correctly to the use of settxfee (paytxfee)
64
64
195
32
31
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_settxfee
test_settxfee
196
206
196
197
854d3556ba9223290caf388c07b9177f88435787
bigcode/the-stack
train
180af1e6f3bb12524147273a
train
function
def test_rebumping_not_replaceable(rbf_node, dest_address): # check that re-bumping a non-replaceable bump tx fails rbfid = spend_one_input(rbf_node, dest_address) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 1000000, "replaceable": False}) assert_raises_jsonrpc(-4, "Transaction is not BIP 125 replacea...
def test_rebumping_not_replaceable(rbf_node, dest_address): # check that re-bumping a non-replaceable bump tx fails
rbfid = spend_one_input(rbf_node, dest_address) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 1000000, "replaceable": False}) assert_raises_jsonrpc(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"], {"totalFee": 2000000})
, rbfid, {"totalFee": 300000}) rbf_node.bumpfee(bumped["txid"], {"totalFee": 300000}) def test_rebumping_not_replaceable(rbf_node, dest_address): # check that re-bumping a non-replaceable bump tx fails
64
64
114
31
33
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_rebumping_not_replaceable
test_rebumping_not_replaceable
217
222
217
218
87ef6bb7c0d5876dc21b822c27f62c99286e6fbf
bigcode/the-stack
train
28a30dbccfe245ea5ba6e7e5
train
function
def test_locked_wallet_fails(rbf_node, dest_address): rbfid = spend_one_input(rbf_node, dest_address) rbf_node.walletlock() assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first.", rbf_node.bumpfee, rbfid)
def test_locked_wallet_fails(rbf_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address) rbf_node.walletlock() assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first.", rbf_node.bumpfee, rbfid)
.bumpfee(rbfid) bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"]) assert_equal(bumped_wtx["comment"], "comment value") assert_equal(bumped_wtx["to"], "to value") def test_locked_wallet_fails(rbf_node, dest_address):
64
64
68
13
51
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_locked_wallet_fails
test_locked_wallet_fails
269
273
269
269
6ed65ad1bfe5d1d1ae6275ee7573574ebf93f93b
bigcode/the-stack
train
3a04b687427d3d385d92c5f2
train
function
def test_rebumping(rbf_node, dest_address): # check that re-bumping the original tx fails, but bumping the bumper succeeds rbfid = spend_one_input(rbf_node, dest_address) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 200000}) assert_raises_jsonrpc(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFe...
def test_rebumping(rbf_node, dest_address): # check that re-bumping the original tx fails, but bumping the bumper succeeds
rbfid = spend_one_input(rbf_node, dest_address) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 200000}) assert_raises_jsonrpc(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 300000}) rbf_node.bumpfee(bumped["txid"], {"totalFee": 300000})
ed_feerate - actual_feerate)) rbf_node.settxfee(Decimal("0.00000000")) # unset paytxfee def test_rebumping(rbf_node, dest_address): # check that re-bumping the original tx fails, but bumping the bumper succeeds
64
64
117
31
32
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_rebumping
test_rebumping
209
214
209
210
960d78c5552d05b0ff218f738f7e1bea189e41ef
bigcode/the-stack
train
2ebbba22522ae432cf2c3b5b
train
function
def test_dust_to_fee(rbf_node, dest_address): # check that if output is reduced to dust, it will be converted to fee # the bumped tx sets fee=49,900, but it converts to 50,000 rbfid = spend_one_input(rbf_node, dest_address) fulltx = rbf_node.getrawtransaction(rbfid, 1) bumped_tx = rbf_node.bumpfee(r...
def test_dust_to_fee(rbf_node, dest_address): # check that if output is reduced to dust, it will be converted to fee # the bumped tx sets fee=49,900, but it converts to 50,000
rbfid = spend_one_input(rbf_node, dest_address) fulltx = rbf_node.getrawtransaction(rbfid, 1) bumped_tx = rbf_node.bumpfee(rbfid, {"totalFee": 4990000}) full_bumped_tx = rbf_node.getrawtransaction(bumped_tx["txid"], 1) assert_equal(bumped_tx["fee"], Decimal("0.050000")) assert_equal(len(fulltx["...
bfid, {"totalFee": 5000001}) def test_dust_to_fee(rbf_node, dest_address): # check that if output is reduced to dust, it will be converted to fee # the bumped tx sets fee=49,900, but it converts to 50,000
64
64
179
52
12
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_dust_to_fee
test_dust_to_fee
184
193
184
186
37e684cfcbd4751a02b49409fd0c4f58854a78c2
bigcode/the-stack
train
ce2121279086b801115eae8c
train
function
def spend_one_input(node, dest_address): tx_input = dict( sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.100000"))) rawtx = node.createrawtransaction( [tx_input], {dest_address: Decimal("0.050000"), node.getrawchangeaddress...
def spend_one_input(node, dest_address):
tx_input = dict( sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.100000"))) rawtx = node.createrawtransaction( [tx_input], {dest_address: Decimal("0.050000"), node.getrawchangeaddress(): Decimal("0.049000")}) signedtx = ...
rbfid = spend_one_input(rbf_node, dest_address) rbf_node.walletlock() assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first.", rbf_node.bumpfee, rbfid) def spend_one_input(node, dest_address):
64
64
118
9
55
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
spend_one_input
spend_one_input
276
284
276
276
3a47ef175d485c8e8b452a6b6c69c77582f90982
bigcode/the-stack
train
976b538025032c221f616576
train
function
def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address): rbfid = spend_one_input(rbf_node, dest_address) rbftx = rbf_node.gettransaction(rbfid) sync_mempools((rbf_node, peer_node)) assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool() bumped_tx = rbf_node.bumpfe...
def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address) rbftx = rbf_node.gettransaction(rbfid) sync_mempools((rbf_node, peer_node)) assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool() bumped_tx = rbf_node.bumpfee(rbfid) assert_equal(bumped_tx["errors"], []) assert bumped_...
) test_rebumping(rbf_node, dest_address) test_rebumping_not_replaceable(rbf_node, dest_address) test_unconfirmed_not_spendable(rbf_node, rbf_node_address) test_bumpfee_metadata(rbf_node, dest_address) test_locked_wallet_fails(rbf_node, dest_address) self.log.info("Success...
97
97
324
19
78
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_simple_bumpfee_succeeds
test_simple_bumpfee_succeeds
85
104
85
85
04dcb8e7ccf1c239a3649e13289a208fe37a8600
bigcode/the-stack
train
0e5b9c766b7cd50031327649
train
function
def test_segwit_bumpfee_succeeds(rbf_node, dest_address): # Create a transaction with segwit output, then create an RBF transaction # which spends it, and make sure bumpfee can be called on it. segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.1")) segwit_out = rbf_node.va...
def test_segwit_bumpfee_succeeds(rbf_node, dest_address): # Create a transaction with segwit output, then create an RBF transaction # which spends it, and make sure bumpfee can be called on it.
segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.1")) segwit_out = rbf_node.validateaddress(rbf_node.getnewaddress()) rbf_node.addwitnessaddress(segwit_out["address"]) segwitid = send_to_witness( use_p2wsh=False, node=rbf_node, utxo=segwit_in, ...
tx = rbf_node.gettransaction(bumped_tx["txid"]) assert_equal(oldwtx["replaced_by_txid"], bumped_tx["txid"]) assert_equal(bumpedwtx["replaces_txid"], rbfid) def test_segwit_bumpfee_succeeds(rbf_node, dest_address): # Create a transaction with segwit output, then create an RBF transaction # which spends i...
102
102
340
52
50
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_segwit_bumpfee_succeeds
test_segwit_bumpfee_succeeds
107
135
107
110
a0ee43688047849cd75ce6620a459d6232d79f7f
bigcode/the-stack
train
519789a6b40af7ab9a9e1f61
train
function
def test_unconfirmed_not_spendable(rbf_node, rbf_node_address): # check that unconfirmed outputs from bumped transactions are not spendable rbfid = spend_one_input(rbf_node, rbf_node_address) rbftx = rbf_node.gettransaction(rbfid)["hex"] assert rbfid in rbf_node.getrawmempool() bumpid = rbf_node.bum...
def test_unconfirmed_not_spendable(rbf_node, rbf_node_address): # check that unconfirmed outputs from bumped transactions are not spendable
rbfid = spend_one_input(rbf_node, rbf_node_address) rbftx = rbf_node.gettransaction(rbfid)["hex"] assert rbfid in rbf_node.getrawmempool() bumpid = rbf_node.bumpfee(rbfid)["txid"] assert bumpid in rbf_node.getrawmempool() assert rbfid not in rbf_node.getrawmempool() # check that outputs fro...
Fee": 300000}) def test_rebumping_not_replaceable(rbf_node, dest_address): # check that re-bumping a non-replaceable bump tx fails rbfid = spend_one_input(rbf_node, dest_address) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 1000000, "replaceable": False}) assert_raises_jsonrpc(-4, "Transaction is not...
152
152
507
32
120
sendycoin-project/sendycoin
test/functional/bumpfee.py
Python
test_unconfirmed_not_spendable
test_unconfirmed_not_spendable
225
258
225
226
9abab349047da49c058e3e4cc34c68f57bbe2ff0
bigcode/the-stack
train
daffa7e416028b91ae3bdbc1
train
class
class RunTime: @classmethod def run_time(cls, logger=print, show_short_result: int = None): """ :param logger: logger func, default is python print :param show_short_result: displays the result of the number of characters. """ def decorator(func): @functools.w...
class RunTime: @classmethod
def run_time(cls, logger=print, show_short_result: int = None): """ :param logger: logger func, default is python print :param show_short_result: displays the result of the number of characters. """ def decorator(func): @functools.wraps(func) def wrapp...
trying(cls, retry_times: int = 3, retry_sleep: int = 0, retry_exceptions: tuple = None, logger=print, sleep_func=time.sleep): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) ...
256
256
1,203
8
247
supplayer/exec_tools
exectools/tools_decorator.py
Python
RunTime
RunTime
63
196
63
64
cc832f4ec167308ab164ffeda0b0285b2550018c
bigcode/the-stack
train
a2aae07975ebc28bf78f4b11
train
class
class TerminableThread(threading.Thread): """a thread that can be stopped by forcing an exception in the execution context""" def terminate(self, exception_cls, repeat_sec=2.0): if self.is_alive() is False: return True killer = ThreadKiller(self, exception_cls, repeat_sec=repeat_sec...
class TerminableThread(threading.Thread):
"""a thread that can be stopped by forcing an exception in the execution context""" def terminate(self, exception_cls, repeat_sec=2.0): if self.is_alive() is False: return True killer = ThreadKiller(self, exception_cls, repeat_sec=repeat_sec) killer.start()
import functools import threading import ctypes import time class TerminableThread(threading.Thread):
20
64
74
8
11
supplayer/exec_tools
exectools/tools_decorator.py
Python
TerminableThread
TerminableThread
7
14
7
7
02f132ccccc20cc3211594c86b713ba956b6035f
bigcode/the-stack
train
8f91f8b3a849966a2679fa2c
train
class
class Retry: @classmethod def trying(cls, retry_times: int = 3, retry_sleep: int = 0, retry_exceptions: tuple = None, logger=print, sleep_func=time.sleep): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: ...
class Retry: @classmethod
def trying(cls, retry_times: int = 3, retry_sleep: int = 0, retry_exceptions: tuple = None, logger=print, sleep_func=time.sleep): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwa...
emon = True def run(self): """loop raising exception incase it's caught hopefully this breaks us far out""" while self.target_thread.is_alive(): ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.target_thread.ident), cty...
77
77
257
7
70
supplayer/exec_tools
exectools/tools_decorator.py
Python
Retry
Retry
35
60
35
36
9ceb40d3b6fc30471e1a1ff78b5ff1a18acf6e8d
bigcode/the-stack
train
b7188a083b9a1a02d9d90bfd
train
class
class ThreadKiller(threading.Thread): """separate thread to kill TerminableThread""" def __init__(self, target_thread, exception_cls, repeat_sec=2.0): threading.Thread.__init__(self) self.target_thread = target_thread self.exception_cls = exception_cls self.repeat_sec = repeat_s...
class ThreadKiller(threading.Thread):
"""separate thread to kill TerminableThread""" def __init__(self, target_thread, exception_cls, repeat_sec=2.0): threading.Thread.__init__(self) self.target_thread = target_thread self.exception_cls = exception_cls self.repeat_sec = repeat_sec self.daemon = True def...
an exception in the execution context""" def terminate(self, exception_cls, repeat_sec=2.0): if self.is_alive() is False: return True killer = ThreadKiller(self, exception_cls, repeat_sec=repeat_sec) killer.start() class ThreadKiller(threading.Thread):
64
64
144
8
56
supplayer/exec_tools
exectools/tools_decorator.py
Python
ThreadKiller
ThreadKiller
17
32
17
17
82a380e143334a648d1c4ebe4259d40e7598c894
bigcode/the-stack
train
721cb38a39b51962ef957142
train
class
class GlobalSearchDocType(Document): pass
class GlobalSearchDocType(Document):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class GlobalSearchDocType(Document):
52
64
9
7
44
ssuda777/frappe
frappe/desk/doctype/global_search_doctype/global_search_doctype.py
Python
GlobalSearchDocType
GlobalSearchDocType
8
9
8
8
9ce9cd0a9d0cc77ab2eae52a92148c958c07d396
bigcode/the-stack
train
af5f86ab88af7eec13a49c33
train
class
class Download(): def __init__(self): super(Download, self).__init__() def load_urls_from_txt_file(self, urls_txt_file): with open(os.path.abspath(urls_txt_file)) as file: urls = file.read().splitlines()
class Download():
def __init__(self): super(Download, self).__init__() def load_urls_from_txt_file(self, urls_txt_file): with open(os.path.abspath(urls_txt_file)) as file: urls = file.read().splitlines()
https://github.com/yunjey/pytorch-tutorial> - <https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Image-Captioning> Thanks Abdulrahman Jamjoom, Yunjey Choi, and Sagar Vinodababu """ import os class Download():
64
64
55
3
60
LuizPitaAlmeida/image_caption_generator
src/data_process/download.py
Python
Download
Download
22
28
22
22
53409a2d059509ebe6480cf705e864c20d7e92da
bigcode/the-stack
train
3eca912b74d7833f325135e8
train
function
def louvain( adata: AnnData, resolution: Optional[float] = None, random_state: Optional[Union[int, RandomState]] = 0, restrict_to: Optional[Tuple[str, Sequence[str]]] = None, key_added: str = 'louvain', adjacency: Optional[spmatrix] = None, flavor: Literal['vtraag', 'igraph', 'rapids'] = 'vt...
def louvain( adata: AnnData, resolution: Optional[float] = None, random_state: Optional[Union[int, RandomState]] = 0, restrict_to: Optional[Tuple[str, Sequence[str]]] = None, key_added: str = 'louvain', adjacency: Optional[spmatrix] = None, flavor: Literal['vtraag', 'igraph', 'rapids'] = 'vt...
"""\ Cluster cells into subgroups [Blondel08]_ [Levine15]_ [Traag17]_. Cluster cells using the Louvain algorithm [Blondel08]_ in the implementation of [Traag17]_. The Louvain algorithm has been proposed for single-cell analysis by [Levine15]_. This requires having ran :func:`~scanpy.pp.neighbo...
from natsort import natsorted from numpy.random.mtrand import RandomState from scipy.sparse import spmatrix from ._utils_clustering import rename_groups, restrict_adjacency from .. import _utils, logging as logg from .._compat import Literal try: from louvain.VertexPartition import MutableVertexPartition except I...
256
256
1,803
156
100
gokceneraslan/scanpy
scanpy/tools/_louvain.py
Python
louvain
louvain
22
224
22
35
17eaa621ff6fd655e06fdd859150b477e4846449
bigcode/the-stack
train
2f399bf3853effe66bcac591
train
class
class EntityClient: def __init__(self): pass def get_matching_kt(self, tgt_api_key, kt_name): filter_params = {'filter[name]': kt_name} result = {'entityFound': False} response = requests.get(GET_APM_KT_URL, headers=self._rest_api_headers(tgt_api_key), params=filter_params) ...
class EntityClient:
def __init__(self): pass def get_matching_kt(self, tgt_api_key, kt_name): filter_params = {'filter[name]': kt_name} result = {'entityFound': False} response = requests.get(GET_APM_KT_URL, headers=self._rest_api_headers(tgt_api_key), params=filter_params) result['status']...
library.utils as utils import library.nrpylogger as nrpy_logger import library.clients.gql as nerdgraph SHOW_APM_APP_URL = 'https://api.newrelic.com/v2/applications/' GET_APM_APP_URL = 'https://api.newrelic.com/v2/applications.json' GET_BROWSER_APP_URL = 'https://api.newrelic.com/v2/browser_applications.json' SHOW_MO...
255
256
4,936
4
251
newrelic-experimental/nrpy
library/clients/entityclient.py
Python
EntityClient
EntityClient
27
587
27
28
456baa91460a96f0e7c157248416e92ab7e3ab0a
bigcode/the-stack
train
b22f9cb41a588f7a64e7577f
train
function
def StringS(name, size, uninitialized=False, explicit_name=False, **kwargs): """ Create a new symbolic string (analogous to z3.String()) :param name: The name of the symbolic string (i. e. the name of the variable) :param size: The size in bytes of the string (i. e. the ...
def StringS(name, size, uninitialized=False, explicit_name=False, **kwargs):
""" Create a new symbolic string (analogous to z3.String()) :param name: The name of the symbolic string (i. e. the name of the variable) :param size: The size in bytes of the string (i. e. the length of the string) :param uninitialized: Whether this value sho...
self.GENERATED_BVS_IDENTIFIER), self.length) else: return BVV(ord(self.args[0]), self.length) def raw_to_fp(self): return self.raw_to_bv().raw_to_fp() def StringS(name, size, uninitialized=False, explicit_name=False, **kwargs):
64
64
214
18
46
saullocarvalho/claripy
claripy/ast/strings.py
Python
StringS
StringS
101
115
101
101
2a0774b379c96243e2278ca8410eb1f35a74b8c6
bigcode/the-stack
train
93ceb1801f596235bc922ca7
train
function
def StringV(value, length=None, **kwargs): """ Create a new Concrete string (analogous to z3.StringVal()) :param value: The constant value of the concrete string :returns: The String object representing the concrete string """ if length is None: length = len(value) ...
def StringV(value, length=None, **kwargs):
""" Create a new Concrete string (analogous to z3.StringVal()) :param value: The constant value of the concrete string :returns: The String object representing the concrete string """ if length is None: length = len(value) if length < len(value): raise ...
, False if explicit_name is None else explicit_name) result = String("StringS", (n, uninitialized), length=size, symbolic=True, eager_backends=None, uninitialized=uninitialized, variables={n}, **kwargs) return result def StringV(value, length=None, **kwargs):
64
64
117
11
52
saullocarvalho/claripy
claripy/ast/strings.py
Python
StringV
StringV
117
133
117
117
15d8e8379ffd1178311a845cbf738978db071dbd
bigcode/the-stack
train
6bccf0f73ff9058ba5e7153f
train
class
class String(Bits): """ Base class that represent the AST of a String object and implements all the operation useful to create and modify the AST. Do not instantiate this class directly, instead use StringS or StringV to construct a symbol or value, and then use operations to construct more complicated...
class String(Bits):
""" Base class that represent the AST of a String object and implements all the operation useful to create and modify the AST. Do not instantiate this class directly, instead use StringS or StringV to construct a symbol or value, and then use operations to construct more complicated expressions. ""...
from .bits import Bits from ..ast.base import _make_name from .. import operations from .bool import Bool from .bv import BV, BVS, BVV class String(Bits):
43
242
808
5
37
saullocarvalho/claripy
claripy/ast/strings.py
Python
String
String
9
98
9
9
d8ab2aa06a7713283a220a431609b70ab6291e19
bigcode/the-stack
train
0dd37fb607b662d2f85d4aaa
train
class
class FCoE_GPSC(Base): __slots__ = () _SDM_NAME = 'fCoEGPSC' _SDM_ATT_MAP = { 'FCoE Header': 'fCoEGPSC.header.fcoeHeader', 'FC Header': 'fCoEGPSC.header.fcHeader', 'FC_CT': 'fCoEGPSC.header.fcCT', 'FCS': 'fCoEGPSC.header.FCS', 'FC CRC': 'fCoEGPSC.header.fcCRC', ...
class FCoE_GPSC(Base):
__slots__ = () _SDM_NAME = 'fCoEGPSC' _SDM_ATT_MAP = { 'FCoE Header': 'fCoEGPSC.header.fcoeHeader', 'FC Header': 'fCoEGPSC.header.fcHeader', 'FC_CT': 'fCoEGPSC.header.fcCT', 'FCS': 'fCoEGPSC.header.FCS', 'FC CRC': 'fCoEGPSC.header.fcCRC', 'FC Trailer': 'fCoEGP...
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class FCoE_GPSC(Base):
26
135
453
8
17
Vibaswan/ixnetwork_restpy
ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/fCoEGPSC_template.py
Python
FCoE_GPSC
FCoE_GPSC
5
51
5
5
8b19f8b70802a3361f55c72e9bcba3291b2e7384
bigcode/the-stack
train
dee37a74e8654791e42284f0
train
class
class MultiDimensionalLSTMTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testMultiDimensionalLSTMAllRNNContainers(self): feature_dims = (3, 4, 5) input_size = feature_dims batch_size = 2 max_length = 8 sequence_length = [4, 6] with self.test...
class MultiDimensionalLSTMTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testMultiDimensionalLSTMAllRNNContainers(self): feature_dims = (3, 4, 5) input_size = feature_dims batch_size = 2 max_length = 8 sequence_length = [4, 6] with self.test_session(graph=ops_lib.Graph()) as sess: i...
(scope_vars), len(all_vars)) def testBidirectionalRNNScope(self): def factory(scope): return self._createBidirectionalRNN( use_shape=True, use_sequence_length=True, scope=scope) self._testScope(factory, use_outer_scope=True) self._testScope(factory, use_outer_scope=False) self._test...
256
256
944
11
245
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
MultiDimensionalLSTMTest
MultiDimensionalLSTMTest
1,540
1,648
1,540
1,541
fa92302cd68c7471700645104af4919bc08160c9
bigcode/the-stack
train
428bf3c6de8f451accef6b3b
train
class
class GRUTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testDynamic(self): time_steps = 8 num_units = 3 input_size = 5 batch_size = 2 input_values = np.random.randn(time_steps, batch_size, input_size) sequence_length = np.random.randint(0,...
class GRUTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testDynamic(self): time_steps = 8 num_units = 3 input_size = 5 batch_size = 2 input_values = np.random.randn(time_steps, batch_size, input_size) sequence_length = np.random.randint(0, time_steps, size=batch_size) ...
_initializer( -0.01, 0.01, seed=self._seed) state_saver = TestStateSaver(batch_size, 2 * num_units) cell = rnn_cell.LSTMCell( num_units, use_peepholes=False, initializer=initializer, state_is_tuple=False) inputs = max_length * [ array_ops.pla...
180
180
603
8
172
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
GRUTest
GRUTest
1,830
1,908
1,830
1,831
3daab463812427db440c9aae13891239036de17d
bigcode/the-stack
train
140c94a0b796008c94c14e57
train
class
class TensorArrayOnCorrectDeviceTest(test.TestCase): def _execute_rnn_on(self, rnn_device=None, cell_device=None, input_device=None): batch_size = 3 time_steps = 7 input_size = 5 num_units = 10 cell = rnn_cell.LSTMCell(num_units, ...
class TensorArrayOnCorrectDeviceTest(test.TestCase):
def _execute_rnn_on(self, rnn_device=None, cell_device=None, input_device=None): batch_size = 3 time_steps = 7 input_size = 5 num_units = 10 cell = rnn_cell.LSTMCell(num_units, use_peepholes=True) gpu_cell = DeviceWrapperCell(c...
: array_ops.zeros([batch_size, input_depth], dtype=dtypes.float32), lambda: inputs_ta.read(time_)) return (elements_finished, next_input, next_state, emit_output, None) return rnn.raw_rnn(cell, loop_fn, scope=scope) self._testScope(factory, use_outer_scope=True) self._testScope(facto...
256
256
948
11
245
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
TensorArrayOnCorrectDeviceTest
TensorArrayOnCorrectDeviceTest
2,236
2,341
2,236
2,237
c1860a2c959ac6c467bf0409f99e96e78c0927bf
bigcode/the-stack
train
808de2b2d580e903ffad86cc
train
class
class BidirectionalRNNTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _createBidirectionalRNN(self, use_shape, use_sequence_length, scope=None): num_units = 3 input_size = 5 batch_size = 2 max_length = 8 initializer = init_ops.random_uniform_ini...
class BidirectionalRNNTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _createBidirectionalRNN(self, use_shape, use_sequence_length, scope=None): num_units = 3 input_size = 5 batch_size = 2 max_length = 8 initializer = init_ops.random_uniform_initializer( -0.01, 0.01, seed=self._se...
.assertAllEqual(value_static, value_dynamic) self.assertAllEqual(state_value_static, state_value_dynamic) if in_graph_mode: self.assertAllEqual(static_grad_values, dynamic_grad_values) self.assertEqual( len(static_individual_grad_values), len(dynamic_individual_grad_values)) ...
256
256
3,474
10
246
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
BidirectionalRNNTest
BidirectionalRNNTest
1,234
1,537
1,234
1,235
66b546d2aa29c9affc47300304f9e50d764b0960
bigcode/the-stack
train
d610aa4310fd848b0a509b4e
train
class
class RNNTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testInvalidSequenceLengthShape(self): cell = Plus1RNNCell() inputs = [array_ops.placeholder(dtypes.float32, shape=(3, 4))] with self.assertRaisesRegexp(ValueError, "must be a vector"): rnn.st...
class RNNTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testInvalidSequenceLengthShape(self): cell = Plus1RNNCell() inputs = [array_ops.placeholder(dtypes.float32, shape=(3, 4))] with self.assertRaisesRegexp(ValueError, "must be a vector"): rnn.static_rnn(cell, inputs, dtype=dt...
): return (5, 5) @property def state_size(self): return (6, 6) def __call__(self, input_, state, scope=None): h, c = state x, y = input_ return ((x + 1, y + 1), (h + 1, c + 1)) class TestStateSaver(object): def __init__(self, batch_size, state_size): self._batch_size = batch_size ...
256
256
1,440
8
248
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
RNNTest
RNNTest
146
301
146
147
3881c315b052c3ee920971e42aa58732460c499c
bigcode/the-stack
train
d01e51f132f8217aac7024b0
train
class
class LSTMTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testNoProjNoSharding(self): num_units = 3 input_size = 5 batch_size = 2 max_length = 8 with self.test_session(use_gpu=True, graph=ops_lib.Graph()) as sess: initializer = init_ops.ran...
class LSTMTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testNoProjNoSharding(self): num_units = 3 input_size = 5 batch_size = 2 max_length = 8 with self.test_session(use_gpu=True, graph=ops_lib.Graph()) as sess: initializer = init_ops.random_uniform_initializer( ...
the variables names starts # with the proper scope. variables_lib.global_variables_initializer() all_vars = variables_lib.global_variables() prefix = prefix or "rnn" scope_vars = [v for v in all_vars if v.name.startswith(prefix + "/")] tf_logging.info("RNN with scope: %s (%s)" % ...
256
256
8,124
8
248
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
LSTMTest
LSTMTest
304
1,231
304
305
8230b7a75fd17ee29a10e15150871446689381b9
bigcode/the-stack
train
2a2733fd9b34898be26145f8
train
class
class NestedLSTMTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testNestedIOLSTMAllRNNContainers(self): input_size = 5 batch_size = 2 state_size = 6 max_length = 8 sequence_length = [4, 6] with self.test_session(graph=ops_lib.Graph()) as sess...
class NestedLSTMTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def testNestedIOLSTMAllRNNContainers(self): input_size = 5 batch_size = 2 state_size = 6 max_length = 8 sequence_length = [4, 6] with self.test_session(graph=ops_lib.Graph()) as sess: state_saver = TestStateSaver(b...
outputs_static_array), axis=2) outputs_bid_array = np.array(outputs_bid_v) self.assertAllEqual(outputs_static_array_double, outputs_bid_array) state_static_v = sess.run( state_static, feed_dict={ inputs[0]: input_value }) state_dynamic_v = sess.run( ...
256
256
1,045
9
247
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
NestedLSTMTest
NestedLSTMTest
1,651
1,771
1,651
1,652
e948c6b22bc17bd59f8356a58b8f72d3c549bb44
bigcode/the-stack
train
59997cbaa8e3344d91bcd75d
train
class
class TestStateSaver(object): def __init__(self, batch_size, state_size): self._batch_size = batch_size self._state_size = state_size self.saved_state = {} def state(self, name): if isinstance(self._state_size, dict): state_size = self._state_size[name] else: state_size = self._st...
class TestStateSaver(object):
def __init__(self, batch_size, state_size): self._batch_size = batch_size self._state_size = state_size self.saved_state = {} def state(self, name): if isinstance(self._state_size, dict): state_size = self._state_size[name] else: state_size = self._state_size if isinstance(stat...
(6, 6) def __call__(self, input_, state, scope=None): h, c = state x, y = input_ return ((x + 1, y + 1), (h + 1, c + 1)) class TestStateSaver(object):
64
64
169
6
58
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
TestStateSaver
TestStateSaver
119
143
119
120
08112f3e08c1414076ae382e7f99ecc7d4488776
bigcode/the-stack
train
771bc1de2a628b64d2846ffc
train
class
class DummyMultiDimensionalLSTM(rnn_lib.RNNCell): """LSTM Cell generating (output, new_state) = (input + 1, state + 1). The input to this cell may have an arbitrary number of dimensions that follow the preceding 'Time' and 'Batch' dimensions. """ def __init__(self, dims): """Initialize the Multi-dimensi...
class DummyMultiDimensionalLSTM(rnn_lib.RNNCell):
"""LSTM Cell generating (output, new_state) = (input + 1, state + 1). The input to this cell may have an arbitrary number of dimensions that follow the preceding 'Time' and 'Batch' dimensions. """ def __init__(self, dims): """Initialize the Multi-dimensional LSTM cell. Args: dims: tuple that ...
1, state + 1).""" @property def output_size(self): return 5 @property def state_size(self): return 5 def __call__(self, input_, state, scope=None): return (input_ + 1, state + 1) class DummyMultiDimensionalLSTM(rnn_lib.RNNCell):
81
81
273
14
67
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
DummyMultiDimensionalLSTM
DummyMultiDimensionalLSTM
64
96
64
64
064de47ba358cd3f668777c79851f75625f44b52
bigcode/the-stack
train
9f1682811bd1a581c2d9aabe
train
class
class DeviceWrapperCell(rnn_cell.RNNCell): """Class to ensure cell calculation happens on a specific device.""" def __init__(self, cell, device): self._cell = cell self._device = device @property def output_size(self): return self._cell.output_size @property def state_size(self): return s...
class DeviceWrapperCell(rnn_cell.RNNCell):
"""Class to ensure cell calculation happens on a specific device.""" def __init__(self, cell, device): self._cell = cell self._device = device @property def output_size(self): return self._cell.output_size @property def state_size(self): return self._cell.state_size def __call__(self, ...
rnn.raw_rnn(cell, loop_fn, scope=scope) self._testScope(factory, use_outer_scope=True) self._testScope(factory, use_outer_scope=False) self._testScope(factory, prefix=None, use_outer_scope=False) class DeviceWrapperCell(rnn_cell.RNNCell):
64
64
146
11
53
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
DeviceWrapperCell
DeviceWrapperCell
2,213
2,233
2,213
2,213
20306b214e8f14158132bc0888ffc1125f92a220
bigcode/the-stack
train
875217f90253f44bb8e3086f
train
class
class Plus1RNNCell(rnn_lib.RNNCell): """RNN Cell generating (output, new_state) = (input + 1, state + 1).""" @property def output_size(self): return 5 @property def state_size(self): return 5 def __call__(self, input_, state, scope=None): return (input_ + 1, state + 1)
class Plus1RNNCell(rnn_lib.RNNCell):
"""RNN Cell generating (output, new_state) = (input + 1, state + 1).""" @property def output_size(self): return 5 @property def state_size(self): return 5 def __call__(self, input_, state, scope=None): return (input_ + 1, state + 1)
_cell from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging from tensorflow.python.util import nest class Plus1RNNCell(...
64
64
96
13
50
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
Plus1RNNCell
Plus1RNNCell
49
61
49
49
f3f5b82fa2101157e98aea4f365c9aedb26f645e
bigcode/the-stack
train
c03b77f172273e734ef4e56c
train
class
class NestedRNNCell(rnn_lib.RNNCell): """RNN Cell generating (output, new_state) = (input + 1, state + 1). The input, output and state of this cell is a tuple of two tensors. """ @property def output_size(self): return (5, 5) @property def state_size(self): return (6, 6) def __call__(self, i...
class NestedRNNCell(rnn_lib.RNNCell):
"""RNN Cell generating (output, new_state) = (input + 1, state + 1). The input, output and state of this cell is a tuple of two tensors. """ @property def output_size(self): return (5, 5) @property def state_size(self): return (6, 6) def __call__(self, input_, state, scope=None): h, c = ...
state_size(self): return self._state_size def __call__(self, input_, state, scope=None): h, c = state return (input_ + 1, (h + 1, c + 1)) class NestedRNNCell(rnn_lib.RNNCell):
64
64
143
12
52
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
NestedRNNCell
NestedRNNCell
99
116
99
99
94995952b9b4360f8b4458c73c09356d3b5f6932
bigcode/the-stack
train