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
c8a8b4fbee308415578b01d0
train
function
def test_back_node(): back_node = BackNode( title="go back", text="returning to ...", level=TO_MAIN ) nested_keyboard = KeyboardNode( title="title", text="text", buttons=[back_node] ) main_keyboard = KeyboardNode( title="title", text="text", buttons=[nested_keyboard] ) ...
def test_back_node():
back_node = BackNode( title="go back", text="returning to ...", level=TO_MAIN ) nested_keyboard = KeyboardNode( title="title", text="text", buttons=[back_node] ) main_keyboard = KeyboardNode( title="title", text="text", buttons=[nested_keyboard] ) assert back_node.g...
KeyboardNode(title="title", text="text", buttons=buttons) assert node.title == "title" assert node.text == "text" assert node.buttons == buttons for button, title in zip(node.buttons, titles): assert button.title == button.text == title def test_back_node():
64
64
91
5
58
Masynchin/textode
tests/test_nodes.py
Python
test_back_node
test_back_node
57
69
57
57
17a091812b130f8c469fef74e3d263de75460289
bigcode/the-stack
train
9a4a90c1860ab667f1e3e38e
train
function
def test_filler_node(): node = FillerNode("both_title_and_text") assert node.title == node.text == "both_title_and_text"
def test_filler_node():
node = FillerNode("both_title_and_text") assert node.title == node.text == "both_title_and_text"
Node, FillerNode, FuncNode, ImageNode, KeyboardNode, TextNode, ) def test_text_node(): node = TextNode(title="title", text="text") assert node.title == "title" assert node.text == "text" def test_filler_node():
64
64
32
6
58
Masynchin/textode
tests/test_nodes.py
Python
test_filler_node
test_filler_node
20
22
20
20
fb67c99a3555adfda33a8a485e8acde41d4e9abc
bigcode/the-stack
train
04dea1886a0fae5ced8f10f1
train
class
@skipIf(NO_MOCK, NO_MOCK_REASON) @patch('servicenow_rest.api.Client', MockServiceNowClient) class ServiceNowModuleTestCase(ModuleTestCase): def setUp(self): hasDependency('servicenow_rest') servicenow.Client = MockServiceNowClient def get_config(service): if service == SERVICE_N...
@skipIf(NO_MOCK, NO_MOCK_REASON) @patch('servicenow_rest.api.Client', MockServiceNowClient) class ServiceNowModuleTestCase(ModuleTestCase):
def setUp(self): hasDependency('servicenow_rest') servicenow.Client = MockServiceNowClient def get_config(service): if service == SERVICE_NAME: return { 'instance_name': 'test', 'username': 'mr_test', 'p...
icenow SERVICE_NAME = 'servicenow' servicenow.__salt__ = {} class MockServiceNowClient(object): def __init__(self, instance_name, username, password): pass def get(self, query): return [{'query_size': len(query), 'query_value': query}] @skipIf(NO_MOCK, NO_MOCK_REASON) @patch...
104
105
350
37
67
velom/salt
tests/unit/modules/test_servicenow.py
Python
ServiceNowModuleTestCase
ServiceNowModuleTestCase
32
72
32
34
a5eac6c205ad7238f1f609652dde5472bd19509b
bigcode/the-stack
train
f691bc7650b2d8cd381437e8
train
class
class MockServiceNowClient(object): def __init__(self, instance_name, username, password): pass def get(self, query): return [{'query_size': len(query), 'query_value': query}]
class MockServiceNowClient(object):
def __init__(self, instance_name, username, password): pass def get(self, query): return [{'query_size': len(query), 'query_value': query}]
from tests.unit import ModuleTestCase, hasDependency from tests.support.mock import ( patch, NO_MOCK, NO_MOCK_REASON ) from salt.modules import servicenow SERVICE_NAME = 'servicenow' servicenow.__salt__ = {} class MockServiceNowClient(object):
63
64
47
7
56
velom/salt
tests/unit/modules/test_servicenow.py
Python
MockServiceNowClient
MockServiceNowClient
23
29
23
23
ecdddde5ff1c19594c89b7824e43b2909e8de560
bigcode/the-stack
train
c6784cb6f1e416b0dc8845de
train
class
class DomainRegistrantFactory(DjangoModelFactory): name = factory.Iterator(['ovh', 'home.pl', 'nazwa.pl']) class Meta: model = DomainRegistrant django_get_or_create = ['name']
class DomainRegistrantFactory(DjangoModelFactory):
name = factory.Iterator(['ovh', 'home.pl', 'nazwa.pl']) class Meta: model = DomainRegistrant django_get_or_create = ['name']
): name = factory.Sequence(lambda n: 'domain-contract{}'.format(n)) class Meta: model = DomainCategory class DomainContractFactory(DjangoModelFactory): domain = factory.SubFactory(DomainFactory) class Meta: model = DomainContract class DomainRegistrantFactory(DjangoModelFactory):
64
64
46
9
54
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DomainRegistrantFactory
DomainRegistrantFactory
52
58
52
53
2c57d5947b1d8e0e2fde4fd6cde24df9e8dfdc44
bigcode/the-stack
train
f6ef6daa92df27fe5bd7f2f4
train
class
class DomainFactory(DjangoModelFactory): name = factory.Sequence(lambda n: 'www.domain{}.com'.format(n)) domain_status = DomainStatus.active technical_owner = factory.SubFactory(UserFactory) business_owner = factory.SubFactory(UserFactory) service_env = factory.SubFactory(ServiceEnvironmentFactory)...
class DomainFactory(DjangoModelFactory):
name = factory.Sequence(lambda n: 'www.domain{}.com'.format(n)) domain_status = DomainStatus.active technical_owner = factory.SubFactory(UserFactory) business_owner = factory.SubFactory(UserFactory) service_env = factory.SubFactory(ServiceEnvironmentFactory) class Meta: model = Domain
alph.assets.tests.factories import ServiceEnvironmentFactory from ralph.domains.models import ( DNSProvider, Domain, DomainCategory, DomainContract, DomainRegistrant, DomainStatus ) from ralph.domains.models.domains import DomainProviderAdditionalServices class DomainFactory(DjangoModelFactory):...
64
64
73
8
55
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DomainFactory
DomainFactory
18
27
18
19
1ebc647ca1e894519937a9d002e28401e31bbe4a
bigcode/the-stack
train
19712e1c5db9f894d8a2fa91
train
class
class DNSProviderFactory(DjangoModelFactory): name = factory.Sequence(lambda n: 'dns-provider{}'.format(n)) class Meta: model = DNSProvider
class DNSProviderFactory(DjangoModelFactory):
name = factory.Sequence(lambda n: 'dns-provider{}'.format(n)) class Meta: model = DNSProvider
.domain{}.com'.format(n)) domain_status = DomainStatus.active technical_owner = factory.SubFactory(UserFactory) business_owner = factory.SubFactory(UserFactory) service_env = factory.SubFactory(ServiceEnvironmentFactory) class Meta: model = Domain class DNSProviderFactory(DjangoModelFactory...
64
64
34
9
54
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DNSProviderFactory
DNSProviderFactory
30
34
30
30
140a9a03330ae180d4a6d0ac814638ce7a32123b
bigcode/the-stack
train
e380b52d328b29ea54edc224
train
class
class DomainProviderAdditionalServicesFactory(DjangoModelFactory): name = factory.Iterator(['Masking', 'Backorder', 'Acquisition']) class Meta: model = DomainProviderAdditionalServices django_get_or_create = ['name']
class DomainProviderAdditionalServicesFactory(DjangoModelFactory):
name = factory.Iterator(['Masking', 'Backorder', 'Acquisition']) class Meta: model = DomainProviderAdditionalServices django_get_or_create = ['name']
: model = DomainContract class DomainRegistrantFactory(DjangoModelFactory): name = factory.Iterator(['ovh', 'home.pl', 'nazwa.pl']) class Meta: model = DomainRegistrant django_get_or_create = ['name'] class DomainProviderAdditionalServicesFactory(DjangoModelFactory):
64
64
49
11
53
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DomainProviderAdditionalServicesFactory
DomainProviderAdditionalServicesFactory
60
65
60
60
63f7bd6b329aadd4c460170f804a50cdc3288fb8
bigcode/the-stack
train
306003080a28a4cd734b871b
train
class
class DomainCategoryFactory(DjangoModelFactory): name = factory.Sequence(lambda n: 'domain-contract{}'.format(n)) class Meta: model = DomainCategory
class DomainCategoryFactory(DjangoModelFactory):
name = factory.Sequence(lambda n: 'domain-contract{}'.format(n)) class Meta: model = DomainCategory
) service_env = factory.SubFactory(ServiceEnvironmentFactory) class Meta: model = Domain class DNSProviderFactory(DjangoModelFactory): name = factory.Sequence(lambda n: 'dns-provider{}'.format(n)) class Meta: model = DNSProvider class DomainCategoryFactory(DjangoModelFactory):
64
64
34
9
54
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DomainCategoryFactory
DomainCategoryFactory
37
41
37
37
ca5e0aaf629c962c71ab54caa0aa0a548426d0ba
bigcode/the-stack
train
db31625fafb86d2de1e65b55
train
class
class DomainContractFactory(DjangoModelFactory): domain = factory.SubFactory(DomainFactory) class Meta: model = DomainContract
class DomainContractFactory(DjangoModelFactory):
domain = factory.SubFactory(DomainFactory) class Meta: model = DomainContract
.Sequence(lambda n: 'dns-provider{}'.format(n)) class Meta: model = DNSProvider class DomainCategoryFactory(DjangoModelFactory): name = factory.Sequence(lambda n: 'domain-contract{}'.format(n)) class Meta: model = DomainCategory class DomainContractFactory(DjangoModelFactory):
64
64
29
9
54
DoNnMyTh/ralph
src/ralph/domains/tests/factories.py
Python
DomainContractFactory
DomainContractFactory
44
49
44
45
ce26010a6436bae1a09be20d9bb5c3e1dbfbf37b
bigcode/the-stack
train
852fc0d8049dd9a934478aaf
train
class
class CDPPlugin(EMUPluginBase): '''Defines CDP plugin ''' plugin_name = 'CDP' # init jsons example for SDK INIT_JSON_NS = {'cdp': {}} """ :parameters: Empty. """ INIT_JSON_CLIENT = {'cdp': {}} """ :parameters: timer: uint32 time in seconds betwean...
class CDPPlugin(EMUPluginBase):
'''Defines CDP plugin ''' plugin_name = 'CDP' # init jsons example for SDK INIT_JSON_NS = {'cdp': {}} """ :parameters: Empty. """ INIT_JSON_CLIENT = {'cdp': {}} """ :parameters: timer: uint32 time in seconds betwean packets ver ...
from trex.emu.api import * from trex.emu.emu_plugins.emu_plugin_base import * import trex.utils.parsing_opts as parsing_opts import json class CDPPlugin(EMUPluginBase):
45
147
490
9
35
Truoris/trex-core
scripts/automation/trex_control_plane/interactive/trex/emu/emu_plugins/emu_plugin_cdp.py
Python
CDPPlugin
CDPPlugin
7
72
7
7
6cbea6cf373bee5063472a4c9205799d815d23d2
bigcode/the-stack
train
fd3e8e64710f3c04148ab17e
train
function
def DFS(cur, n): visited = [0 for _ in range(n)] stack = [cur] cnt = 1 visited[cur] = 1 while stack: cur = stack.pop() jump = stone[cur] for next in (cur + jump, cur - jump): if not 0 <= next < n: # 돌다리 밖으로 나가는 경우 continue if visited[next] == 0: visited[next] = 1 cnt += 1 stack.append(...
def DFS(cur, n):
visited = [0 for _ in range(n)] stack = [cur] cnt = 1 visited[cur] = 1 while stack: cur = stack.pop() jump = stone[cur] for next in (cur + jump, cur - jump): if not 0 <= next < n: # 돌다리 밖으로 나가는 경우 continue if visited[next] == 0: visited[next] = 1 cnt += 1 stack.append(next) return cnt...
# functions def DFS(cur, n):
9
64
119
6
2
WaiNaat/BOJ-Python
14248_stack_v2.py
Python
DFS
DFS
2
18
2
2
bbcf8048d84c3e6f19cc655b25e3de30db2062bb
bigcode/the-stack
train
8658148e0e80e1518f805bd5
train
function
def data_type(): return tf.float16 if FLAGS.use_fp16 else tf.float32
def data_type():
return tf.float16 if FLAGS.use_fp16 else tf.float32
num_layers = 1 num_steps = 20 hidden_size = 200 max_epoch = 4 max_max_epoch = 20 keep_prob = 1 lr_decay = 0.95 batch_size = 64 def data_type():
64
64
19
4
59
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
data_type
data_type
68
69
68
68
acca195dd3ee89f85e301e84823e54e40601ee8f
bigcode/the-stack
train
b154fd241c876681dec31d4d
train
class
class Config(object): """Small config.""" init_scale = 0.1 learning_rate = 0.2 max_grad_norm = 1 num_layers = 1 num_steps = 20 hidden_size = 200 max_epoch = 4 max_max_epoch = 20 keep_prob = 1 lr_decay = 0.95 batch_size = 64
class Config(object):
"""Small config.""" init_scale = 0.1 learning_rate = 0.2 max_grad_norm = 1 num_layers = 1 num_steps = 20 hidden_size = 200 max_epoch = 4 max_max_epoch = 20 keep_prob = 1 lr_decay = 0.95 batch_size = 64
, "Where the wordlist file is stored.") flags.DEFINE_string("save-path", None, "Model output directory.") flags.DEFINE_bool("use-fp16", False, "Train using 16-bit floats instead of 32bit floats") FLAGS = flags.FLAGS class Config(object):
64
64
94
4
59
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
Config
Config
54
66
54
54
5237a70e1c9dc8565f7b84df6956428da7d82c16
bigcode/the-stack
train
d28b881f84cac351d6c1d068
train
class
class RnnlmModel(object): """The RNNLM model.""" def __init__(self, is_training, config, input_): self._input = input_ batch_size = input_.batch_size num_steps = input_.num_steps size = config.hidden_size vocab_size = config.vocab_size def rnn_cell(): # With the latest TensorFlow so...
class RnnlmModel(object):
"""The RNNLM model.""" def __init__(self, is_training, config, input_): self._input = input_ batch_size = input_.batch_size num_steps = input_.num_steps size = config.hidden_size vocab_size = config.vocab_size def rnn_cell(): # With the latest TensorFlow source code (as of Mar 27, 2...
output directory.") flags.DEFINE_bool("use-fp16", False, "Train using 16-bit floats instead of 32bit floats") FLAGS = flags.FLAGS class Config(object): """Small config.""" init_scale = 0.1 learning_rate = 0.2 max_grad_norm = 1 num_layers = 1 num_steps = 20 hidden_size = 200 max_epoc...
256
256
1,433
7
249
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
RnnlmModel
RnnlmModel
82
236
82
82
67e86f5087028657bce5bd3376194fd4b7adecc4
bigcode/the-stack
train
6da874c4d402aa7794b872da
train
class
class RnnlmInput(object): """The input data.""" def __init__(self, config, data, name=None): self.batch_size = batch_size = config.batch_size self.num_steps = num_steps = config.num_steps self.epoch_size = ((len(data) // batch_size) - 1) // num_steps self.input_data, self.targets = reader.rnnlm_pro...
class RnnlmInput(object):
"""The input data.""" def __init__(self, config, data, name=None): self.batch_size = batch_size = config.batch_size self.num_steps = num_steps = config.num_steps self.epoch_size = ((len(data) // batch_size) - 1) // num_steps self.input_data, self.targets = reader.rnnlm_producer( data, batch...
max_epoch = 4 max_max_epoch = 20 keep_prob = 1 lr_decay = 0.95 batch_size = 64 def data_type(): return tf.float16 if FLAGS.use_fp16 else tf.float32 class RnnlmInput(object):
64
64
100
7
56
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
RnnlmInput
RnnlmInput
72
80
72
72
2982f5d92c2f3d7d1542d8804d22ece85bed1ef4
bigcode/the-stack
train
efd340c56035cda287a0daa4
train
function
def main(_): if not FLAGS.data_path: raise ValueError("Must set --data_path to RNNLM data directory") raw_data = reader.rnnlm_raw_data(FLAGS.data_path, FLAGS.vocab_path) train_data, valid_data, _, word_map = raw_data config = get_config() config.hidden_size = FLAGS.hidden_size config.vocab_size = len(...
def main(_):
if not FLAGS.data_path: raise ValueError("Must set --data_path to RNNLM data directory") raw_data = reader.rnnlm_raw_data(FLAGS.data_path, FLAGS.vocab_path) train_data, valid_data, _, word_map = raw_data config = get_config() config.hidden_size = FLAGS.hidden_size config.vocab_size = len(word_map) e...
.initial_state): feed_dict[h] = state[i] vals = session.run(fetches, feed_dict) cost = vals["cost"] state = vals["final_state"] costs += cost iters += model.input.num_steps if verbose and step % (model.input.epoch_size // 10) == 10: print("%.3f perplexity: %.3f speed: %.0f wps" % ...
154
154
515
4
150
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
main
main
275
323
275
275
1a03eda99a5ca65fe3dd45dd6b0e77d5b8b98458
bigcode/the-stack
train
8a81aebdef83c1587733e4a8
train
function
def run_epoch(session, model, eval_op=None, verbose=False): """Runs the model on the given data.""" start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = { "cost": model.cost, "final_state": model.final_state, } if eval_op is not None: fetches...
def run_epoch(session, model, eval_op=None, verbose=False):
"""Runs the model on the given data.""" start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = { "cost": model.cost, "final_state": model.final_state, } if eval_op is not None: fetches["eval_op"] = eval_op for step in range(model.input.epoch...
@property def cost(self): return self._cost @property def final_state(self): return self._final_state @property def lr(self): return self._lr @property def train_op(self): return self._train_op def run_epoch(session, model, eval_op=None, verbose=False):
78
78
263
14
63
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
run_epoch
run_epoch
238
269
238
238
e55415b7958c8d0a29bcce9dbeff9fde4adacf5b
bigcode/the-stack
train
4f336c06abb8b935ae82779f
train
function
def get_config(): return Config()
def get_config():
return Config()
f speed: %.0f wps" % (step * 1.0 / model.input.epoch_size, np.exp(costs / iters), iters * model.input.batch_size / (time.time() - start_time))) return np.exp(costs / iters) def get_config():
64
64
8
4
60
tearyl/tramkaldi
egs/wsj/s5/steps/tfrnnlm/vanilla_rnnlm.py
Python
get_config
get_config
272
273
272
272
5f52c08af7f2cceb8c27233e7c388499eeaa7155
bigcode/the-stack
train
fd99384e4afedc45527e1818
train
function
def _set_task_progress(progress): job = get_current_job() if job: print(f'Job: {job}') job.meta['progress'] = progress job.save_meta() print(f'task id: {job.get_id()}') task = Task.query.get(job.get_id()) print(f'Task: {task}') task.user.add_notificatio...
def _set_task_progress(progress):
job = get_current_job() if job: print(f'Job: {job}') job.meta['progress'] = progress job.save_meta() print(f'task id: {job.get_id()}') task = Task.query.get(job.get_id()) print(f'Task: {task}') task.user.add_notification('task_progress', ...
.delete(comms) #db.session.delete(u) u.email=None u.goog_id=None u.firstname = None u.username = None u.add_by_email=None u.token=None u.deleted=True db.session.commit() def _set_task_progress(progress):
64
64
116
7
57
Roznoshchik/Lurnby
app/tasks.py
Python
_set_task_progress
_set_task_progress
58
73
58
58
0ee58e18707efab2d56f912633bb40dbb28421ca
bigcode/the-stack
train
bd0a9aaf70e3a8a5d50aee3b
train
function
def bg_add_article(u, a_id, pdf, epub, tags): try: _set_task_progress(0) today = date.today() today = today.strftime("%B %d, %Y") basedir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join( basedir, 'temp' ) if not os.path.i...
def bg_add_article(u, a_id, pdf, epub, tags):
try: _set_task_progress(0) today = date.today() today = today.strftime("%B %d, %Y") basedir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join( basedir, 'temp' ) if not os.path.isdir(path): os.mkdir(path) ...
% (location, bucket, az_path) url = s3.generate_presigned_url('get_object', Params = {'Bucket': bucket, 'Key': az_path}, ExpiresIn = 604800) print(f'sending email - [Lurnby] Your exported data for user: {user.id}') send_email('[Lurnby] Your exported highlights', ...
179
180
603
15
164
Roznoshchik/Lurnby
app/tasks.py
Python
bg_add_article
bg_add_article
256
345
256
256
375dff324edff7958f6f61cc9148df8063bb82f3
bigcode/the-stack
train
362c0d28e890178929169232
train
function
def export_highlights(user, highlights, source, ext): if not highlights: return try: _set_task_progress(0) data = [] i = 0 total_highlights = len(highlights) basedir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join( bas...
def export_highlights(user, highlights, source, ext):
if not highlights: return try: _set_task_progress(0) data = [] i = 0 total_highlights = len(highlights) basedir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join( basedir, 'temp' ) if not os.path.isdir(p...
/export_highlights.txt', url=url, user=user, delete_date=delete_date), html_body=render_template('email/export_highlights.html', url=url, user=user, delete_date=delete_date), sync=True) if delete: # if os.environ.get('DEV'): # az_path_base = f'...
255
256
1,212
12
243
Roznoshchik/Lurnby
app/tasks.py
Python
export_highlights
export_highlights
133
253
133
133
5866e38a0c991a51ef31d7820ea7d498960e1569
bigcode/the-stack
train
12831ff774f318b61b777384
train
function
def set_images_lazy(aid): try: _set_task_progress(0) a = Article.query.get(aid) soup = BeautifulSoup(a.content, "html5lib") images = soup.find_all("img") for img in images: img["loading"] = "lazy" a.content = str(soup.prettify()) db.session.commit(...
def set_images_lazy(aid):
try: _set_task_progress(0) a = Article.query.get(aid) soup = BeautifulSoup(a.content, "html5lib") images = soup.find_all("img") for img in images: img["loading"] = "lazy" a.content = str(soup.prettify()) db.session.commit() except: app....
.archived: t.archived = False new_article.AddToTag(t) db.session.commit() os.remove(path) except: app.logger.error('Unhandled exception', exc_info=sys.exc_info()) finally: _set_task_progress(100) def set_images_laz...
64
64
108
7
57
Roznoshchik/Lurnby
app/tasks.py
Python
set_images_lazy
set_images_lazy
347
360
347
347
3d560655b13783d756afc2974e2cc1aece2d6bc3
bigcode/the-stack
train
df1fbff9216419b10b7f1063
train
function
def delete_user(u): highlights=u.highlights.all() topics = u.topics.all() articles = u.articles.all() tags = u.tags.all() senders = u.approved_senders.all() comms = u.comms for h in highlights: db.session.execute(f'DELETE from highlights_topics where highlight_id={h.id}') db....
def delete_user(u):
highlights=u.highlights.all() topics = u.topics.all() articles = u.articles.all() tags = u.tags.all() senders = u.approved_senders.all() comms = u.comms for h in highlights: db.session.execute(f'DELETE from highlights_topics where highlight_id={h.id}') db.session.execute(f'DE...
BeautifulSoup import re from app import create_app, db, s3, bucket from app.export import get_zip from app.email import send_email from app.main.ebooks import epubTitle, epubConverted from app.main.pdf import importPDF from app.models import Task, Article, Highlight, Tag, User, Event app = create_app() app.app_con...
85
85
285
5
80
Roznoshchik/Lurnby
app/tasks.py
Python
delete_user
delete_user
23
55
23
23
b7650574d22460841c77dda16d6c80a5c6644437
bigcode/the-stack
train
390666a426cf27f55db2f59a
train
function
def account_export(uid, ext, delete=False): try: _set_task_progress(0) user = User.query.get(uid) if ext != 'none': print('exporting') if os.environ.get('DEV'): az_path_base = f'staging/{user.id}/exports/' else: az_path_base...
def account_export(uid, ext, delete=False):
try: _set_task_progress(0) user = User.query.get(uid) if ext != 'none': print('exporting') if os.environ.get('DEV'): az_path_base = f'staging/{user.id}/exports/' else: az_path_base = f'{user.id}/exports/' filenam...
.firstname = None u.username = None u.add_by_email=None u.token=None u.deleted=True db.session.commit() def _set_task_progress(progress): job = get_current_job() if job: print(f'Job: {job}') job.meta['progress'] = progress job.save_meta() print(f'task id:...
158
158
529
10
148
Roznoshchik/Lurnby
app/tasks.py
Python
account_export
account_export
76
129
76
76
38b0a3d4250e6542d0cc68467dfe00713b04ef46
bigcode/the-stack
train
3cdbe63e8af65a86c6e86fd0
train
function
def create_recall_text(highlightId): highlight = Highlight.query.filter_by(id=highlightId).first() soup = BeautifulSoup(highlight.text, features='lxml') for text in soup.find_all(text=True): words = text.split(' ') if (len(words) > 3): for i in range(0,len(words) // 3): ...
def create_recall_text(highlightId):
highlight = Highlight.query.filter_by(id=highlightId).first() soup = BeautifulSoup(highlight.text, features='lxml') for text in soup.find_all(text=True): words = text.split(' ') if (len(words) > 3): for i in range(0,len(words) // 3): num = randint(0, len(words) -1...
ify()) db.session.commit() except: app.logger.error('Unhandled exception', exc_info=sys.exc_info()) finally: _set_task_progress(100) # Also consider changing the algorithm for finding the spaces # to be a bit more sophisticated. def create_recall_text(highlightId):
64
64
133
9
55
Roznoshchik/Lurnby
app/tasks.py
Python
create_recall_text
create_recall_text
391
403
391
391
51238c24515d72c2021f80a84a3dacc0e15d1dae
bigcode/the-stack
train
6dc26462e830a0f45cd58b65
train
function
def set_absolute_urls(aid): try: _set_task_progress(0) a = Article.query.get(aid) if a.source_url: soup = BeautifulSoup(a.content, "html5lib") images = soup.find_all("img") for img in images: try: if 'http' not in img['s...
def set_absolute_urls(aid):
try: _set_task_progress(0) a = Article.query.get(aid) if a.source_url: soup = BeautifulSoup(a.content, "html5lib") images = soup.find_all("img") for img in images: try: if 'http' not in img['src']: ...
img in images: img["loading"] = "lazy" a.content = str(soup.prettify()) db.session.commit() except: app.logger.error('Unhandled exception', exc_info=sys.exc_info()) finally: _set_task_progress(100) def set_absolute_urls(aid):
64
64
204
7
57
Roznoshchik/Lurnby
app/tasks.py
Python
set_absolute_urls
set_absolute_urls
362
387
362
362
fd752e915e6926930cf498431b56645993bb4f07
bigcode/the-stack
train
90d23927024fcbdfea9d00af
train
function
def data_processing_sex_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Sex', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
def data_processing_sex_sort(file):
df = data_processing_rename(file) df2 = ( df.sort_values('Sex', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
(file): df = data_processing_rename(file) df2 = ( df.sort_values('Age', ascending = True) #sorts the data by age .reset_index(drop = True) #resets the index ) return df2 def data_processing_sex_sort(file):
64
64
62
8
55
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_sex_sort
data_processing_sex_sort
16
22
16
16
97055833ceb33ba7917118e7c654e98c435eb140
bigcode/the-stack
train
ffca6b269c49888991e9dfbb
train
function
def data_processing_smoker_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Smoker', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
def data_processing_smoker_sort(file):
df = data_processing_rename(file) df2 = ( df.sort_values('Smoker', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
(file): df = data_processing_rename(file) df2 = ( df.sort_values('Children', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2 def data_processing_smoker_sort(file):
64
64
62
8
55
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_smoker_sort
data_processing_smoker_sort
40
46
40
40
b6b9764b9989943ef52cdad6b083e394aa76f758
bigcode/the-stack
train
0459d78617dd796255ad0263
train
function
def data_processing_age_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Age', ascending = True) #sorts the data by age .reset_index(drop = True) #resets the index ) return df2
def data_processing_age_sort(file):
df = data_processing_rename(file) df2 = ( df.sort_values('Age', ascending = True) #sorts the data by age .reset_index(drop = True) #resets the index ) return df2
pd.read_csv(file) df2 = df.rename(columns = {'age':'Age', 'sex':'Sex', 'bmi':'BMI', 'children':'Children', 'smoker':'Smoker', 'region':'Region', 'charges':'Medical Costs'}) return df2 def data_processing_age_sort(file):
64
64
61
7
56
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_age_sort
data_processing_age_sort
8
14
8
8
09f4c16deca1499f07a149304b11c57c1a8b59a3
bigcode/the-stack
train
2821d5d7998ac297224d70f6
train
function
def data_processing_rename(file): df = pd.read_csv(file) df2 = df.rename(columns = {'age':'Age', 'sex':'Sex', 'bmi':'BMI', 'children':'Children', 'smoker':'Smoker', 'region':'Region', 'charges':'Medical Costs'}) return df2
def data_processing_rename(file):
df = pd.read_csv(file) df2 = df.rename(columns = {'age':'Age', 'sex':'Sex', 'bmi':'BMI', 'children':'Children', 'smoker':'Smoker', 'region':'Region', 'charges':'Medical Costs'}) return df2
import pandas as pd def data_processing_rename(file):
12
64
67
7
4
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_rename
data_processing_rename
3
6
3
3
c2398aa8b74c7831780700436016186b9cb6aa58
bigcode/the-stack
train
ec5d0c4007be643122c474ee
train
function
def data_processing_region_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Region', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
def data_processing_region_sort(file):
df = data_processing_rename(file) df2 = ( df.sort_values('Region', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Sex', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2 def data_processing_region_sort(file):
64
64
61
7
56
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_region_sort
data_processing_region_sort
24
30
24
24
0af3477f94a162bb58532118958ac73167306949
bigcode/the-stack
train
a63c615f3ca192f6c6320ab4
train
function
def data_processing_children_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Children', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
def data_processing_children_sort(file):
df = data_processing_rename(file) df2 = ( df.sort_values('Children', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2
_sort(file): df = data_processing_rename(file) df2 = ( df.sort_values('Region', ascending = True) #sorts the data by region .reset_index(drop = True) #resets the index ) return df2 def data_processing_children_sort(file):
64
64
61
7
56
data301-2020-winter2/course-project-group_1042
analysis/Luis/.ipynb_checkpoints/project_functions-checkpoint.py
Python
data_processing_children_sort
data_processing_children_sort
32
38
32
32
373215ee9626ba6adce11d0aae9fe60d7b576a2c
bigcode/the-stack
train
7a75e94f5455616add4b9311
train
function
def _nothing (value): return value
def _nothing (value):
return value
Style: {color: 'black', fontSize: 10} }, }; var chart = new google.visualization.LineChart(document.getElementById('chart_div_%(ident)s')); chart.draw(data, options); } </script> """ def _nothing (value):
64
64
9
7
57
oriolarcas/exaproxy
lib/exaproxy/html/graph.py
Python
_nothing
_nothing
43
43
43
43
1418f086cbede2b81e240f9779805fbe0d980593
bigcode/the-stack
train
a42a345989b723c2feb6c05a
train
function
def graph (monitor,title,reload_time,_keys,cumulative=False,split=False,adaptor=_nothing): page = _chart_header % reload_time + '<div>' keys = [[_] for _ in _keys] if split else [_keys] for ident, interval,ratio in (('seconds','Seconds',1),('minutes','Minutes',60)): data = [] datasource = getattr(monitor,ident)...
def graph (monitor,title,reload_time,_keys,cumulative=False,split=False,adaptor=_nothing):
page = _chart_header % reload_time + '<div>' keys = [[_] for _ in _keys] if split else [_keys] for ident, interval,ratio in (('seconds','Seconds',1),('minutes','Minutes',60)): data = [] datasource = getattr(monitor,ident) for k in keys: columns = "data.addColumn('number', '%s');\n" % interval + '\n'.join([...
Rows([ %(values)s ]); var options = { width: 480, height: 500, title: '%(title)s', legend : { position: 'bottom', textStyle: {color: 'black', fontSize: 10} }, }; var chart = new google.visualization.LineChart(document.getElementById('chart_div_%(ident)s')); chart.draw(data, options); } ...
134
134
448
22
111
oriolarcas/exaproxy
lib/exaproxy/html/graph.py
Python
graph
graph
45
87
45
45
b0c175c982491c7853658d2592d63ab0a6e50f4e
bigcode/the-stack
train
db750564cf9f0c5db13acc11
train
function
def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = '{{ project_name }}/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Una...
def get_version():
""" Extracts the version number from the version.py file. """ VERSION_FILE = '{{ project_name }}/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Unable to find version...
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215) import multiprocessing assert multiprocessing import re from setuptools import setup, find_packages def get_version():
43
64
100
4
38
wesleykendall/ambition-python-template
setup.py
Python
get_version
get_version
8
17
8
8
d3a31927e3a85232d54549f2e0d90cc6c8252a41
bigcode/the-stack
train
512b6397daffe02cbacf9aa3
train
function
def get_api_session(): return app.api_session
def get_api_session():
return app.api_session
else: return False def list_players(self): ret = [] for k, v in self._pending_players.items: ret.append(v.get_alias()) return ret app = Flask(__name__) app.api_session = ApiSession() app.lobby = GameLobby() def get_api_session():
64
64
11
5
59
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
get_api_session
get_api_session
90
91
90
90
6c35cf36fb200587dfb688531550a15ac3c17d5c
bigcode/the-stack
train
897dbe94ab00c0a5f45e38ca
train
function
@app.route('/game/login', methods=["POST"]) def login(): """ log into the game lobby """ user = request.args['user'] if 'user' in request.args else '' passw = request.args['pass'] if 'pass' in request.args else '' token = get_api_session().login(user, passw) if token: return jsonify({'statu...
@app.route('/game/login', methods=["POST"]) def login():
""" log into the game lobby """ user = request.args['user'] if 'user' in request.args else '' passw = request.args['pass'] if 'pass' in request.args else '' token = get_api_session().login(user, passw) if token: return jsonify({'status': 'OK', 'token': token}) print("bad login") abo...
.append(v.get_alias()) return ret app = Flask(__name__) app.api_session = ApiSession() app.lobby = GameLobby() def get_api_session(): return app.api_session def get_lobby(): return app.lobby @app.route('/game/login', methods=["POST"]) def login():
64
64
98
13
50
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
login
login
98
108
98
99
48ab80cf5bbb7a94af5b0b16bb447894cb347364
bigcode/the-stack
train
126e20bec454cb81e351d79e
train
function
@app.route("/game/unregister", methods=["POST"]) def unregister(): """ unregister as a player candidate""" session = get_api_session().get_session(request) if not session: abort(401) user = session['user'] lobby = get_lobby() if not lobby.unregister(user): abort(400) return...
@app.route("/game/unregister", methods=["POST"]) def unregister():
""" unregister as a player candidate""" session = get_api_session().get_session(request) if not session: abort(401) user = session['user'] lobby = get_lobby() if not lobby.unregister(user): abort(400) return jsonify({'status': 'OK'})
'] alias = request.args['alias'] if 'alias' in request.args else user lobby = get_lobby() if not lobby.register(user, alias): abort(400) return jsonify({'status': 'OK'}) @app.route("/game/unregister", methods=["POST"]) def unregister():
63
64
78
14
49
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
unregister
unregister
141
153
141
142
3c5ed0bcd594ff6b20fd1755bd387bdf3f464b24
bigcode/the-stack
train
142491caacc85e516898a923
train
function
@app.route('/game/logout', methods=["POST"]) def logout(): """ log out and forget about the user """ session = get_api_session().get_session(request) if not session: abort(401) get_lobby().unregister(session['user']) get_api_session().logout(session['token']) return jsonify({'status': ...
@app.route('/game/logout', methods=["POST"]) def logout():
""" log out and forget about the user """ session = get_api_session().get_session(request) if not session: abort(401) get_lobby().unregister(session['user']) get_api_session().logout(session['token']) return jsonify({'status': 'OK'})
if 'pass' in request.args else '' token = get_api_session().login(user, passw) if token: return jsonify({'status': 'OK', 'token': token}) print("bad login") abort(401) @app.route('/game/logout', methods=["POST"]) def logout():
64
64
74
13
51
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
logout
logout
111
121
111
112
d9c5d4905c34fa191641c8e9ad1d6898438b872c
bigcode/the-stack
train
1c8c023fe2a2fd0634d51e9f
train
class
class ApiSession: CREDENTIALS = { 'markku': '3l1t3', 'guest': 'lam3' } def __init__(self): self._sessions = {} def login(self, user, passw): if user in self.CREDENTIALS: exp_pass = self.CREDENTIALS[user] if passw == exp_pass: to...
class ApiSession:
CREDENTIALS = { 'markku': '3l1t3', 'guest': 'lam3' } def __init__(self): self._sessions = {} def login(self, user, passw): if user in self.CREDENTIALS: exp_pass = self.CREDENTIALS[user] if passw == exp_pass: token = self._new_ses...
#!/usr/bin/env python3 from flask import Flask, jsonify, request, abort class ApiSession:
22
68
229
4
17
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
ApiSession
ApiSession
5
42
5
6
34c41627d3d6b9cd907ae046a9c038025a8d5e2c
bigcode/the-stack
train
9a3b6cde924f2df20153b523
train
class
class GameLobby: def __init__(self): self._pending_players = {} def register(self, user, alias): if user not in self._pending_players: player = Player(user, alias) self._pending_players[user] = player return True else: return False de...
class GameLobby:
def __init__(self): self._pending_players = {} def register(self, user, alias): if user not in self._pending_players: player = Player(user, alias) self._pending_players[user] = player return True else: return False def unregister(self...
token # todo session expiry class Player: def __init__(self, user, alias): self._user = user self._alias = alias def get_user(self): return self._user def get_alias(self): return self._alias class GameLobby:
64
64
134
4
59
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
GameLobby
GameLobby
59
82
59
59
9fea71faad656618dc6c5f25ff665e263c106086
bigcode/the-stack
train
cadb04cd8f024b57bb8f96ef
train
function
def get_lobby(): return app.lobby
def get_lobby():
return app.lobby
): ret = [] for k, v in self._pending_players.items: ret.append(v.get_alias()) return ret app = Flask(__name__) app.api_session = ApiSession() app.lobby = GameLobby() def get_api_session(): return app.api_session def get_lobby():
64
64
11
5
58
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
get_lobby
get_lobby
94
95
94
94
f140333fd8e0e96518e48468cdd0a04203406d2a
bigcode/the-stack
train
8e0dc2c6497ff714f278c8da
train
class
class Player: def __init__(self, user, alias): self._user = user self._alias = alias def get_user(self): return self._user def get_alias(self): return self._alias
class Player:
def __init__(self, user, alias): self._user = user self._alias = alias def get_user(self): return self._user def get_alias(self): return self._alias
_session(self, user): with open("/dev/urandom", "rb") as f: rnd = f.read(16) token = rnd.hex() self._sessions[token] = {"user": user, "token": token} return token # todo session expiry class Player:
64
64
52
3
60
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
Player
Player
46
56
46
47
dcef70d428c75f70f69b76708a085ff70e9c4752
bigcode/the-stack
train
33f66080fdd1891568994492
train
function
@app.route("/game/register", methods=["POST"]) def register(): """ register caller into game lobby as a player candidate""" session = get_api_session().get_session(request) if not session: abort(401) user = session['user'] alias = request.args['alias'] if 'alias' in request.args else user ...
@app.route("/game/register", methods=["POST"]) def register():
""" register caller into game lobby as a player candidate""" session = get_api_session().get_session(request) if not session: abort(401) user = session['user'] alias = request.args['alias'] if 'alias' in request.args else user lobby = get_lobby() if not lobby.register(user, alias)...
session = get_api_session().get_session(request) if not session: abort(401) get_lobby().unregister(session['user']) get_api_session().logout(session['token']) return jsonify({'status': 'OK'}) @app.route("/game/register", methods=["POST"]) def register():
63
64
101
13
50
markkudegerholmknowit/pytest-tracerobot
example/gameserver.py
Python
register
register
124
138
124
125
d103cc409f6913b8e4189d1ef36b2ed4038fc645
bigcode/the-stack
train
06d4f387e41b1424d1b8503c
train
function
def run_server(): options = get_options() configure_app(flatdb_app, options) from gevent.pywsgi import WSGIServer server = WSGIServer((options.host, options.port), flatdb_app) server.serve_forever()
def run_server():
options = get_options() configure_app(flatdb_app, options) from gevent.pywsgi import WSGIServer server = WSGIServer((options.host, options.port), flatdb_app) server.serve_forever()
configure_app(app, options): app.config['DB'] = options.database define_urls(app) def dev_server(): options = get_options() configure_app(flatdb_app, options) flatdb_app.run(debug=options.debug, port=options.port, host=options.host) def run_server():
64
64
57
4
60
TodaysMeet/flatdb
flatdb/run.py
Python
run_server
run_server
27
34
27
27
f6d2cc5c0c2b5e1ee0d3343aa653c05ac8e79dfc
bigcode/the-stack
train
74200f119e9c9033c0eaea28
train
function
def dev_server(): options = get_options() configure_app(flatdb_app, options) flatdb_app.run(debug=options.debug, port=options.port, host=options.host)
def dev_server():
options = get_options() configure_app(flatdb_app, options) flatdb_app.run(debug=options.debug, port=options.port, host=options.host)
2) parser.add_argument('-b', '--database') parser.add_argument('-H', '--host', default='127.0.0.1') return parser.parse_args() def configure_app(app, options): app.config['DB'] = options.database define_urls(app) def dev_server():
64
64
39
4
60
TodaysMeet/flatdb
flatdb/run.py
Python
dev_server
dev_server
21
24
21
21
09857418cfa22b76e10ec33c40237ae2545fd658
bigcode/the-stack
train
6e44256e09269fa6e00b8d3f
train
function
def get_options(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', default=False) parser.add_argument('-p', '--port', type=int, default=7532) parser.add_argument('-b', '--database') parser.add_argument('-H', '--host', default='127.0.0.1') return parse...
def get_options():
parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', default=False) parser.add_argument('-p', '--port', type=int, default=7532) parser.add_argument('-b', '--database') parser.add_argument('-H', '--host', default='127.0.0.1') return parser.parse_args()
import argparse from flatdb import flatdb_app from flatdb.app import define_urls def get_options():
23
64
83
4
18
TodaysMeet/flatdb
flatdb/run.py
Python
get_options
get_options
7
13
7
7
07fe82823fe76be38e72a4c69524e09abf5a88a0
bigcode/the-stack
train
8b20dc44ca548a8a95b9e3e8
train
function
def configure_app(app, options): app.config['DB'] = options.database define_urls(app)
def configure_app(app, options):
app.config['DB'] = options.database define_urls(app)
default=False) parser.add_argument('-p', '--port', type=int, default=7532) parser.add_argument('-b', '--database') parser.add_argument('-H', '--host', default='127.0.0.1') return parser.parse_args() def configure_app(app, options):
64
64
22
7
57
TodaysMeet/flatdb
flatdb/run.py
Python
configure_app
configure_app
16
18
16
16
a1c58fbd61907705e12f98b45721b5388e747fd0
bigcode/the-stack
train
7488de49809cb9877ca1399c
train
class
@params_type(SplitParameters) @in_qs_constraint({'dtype': set([np.int8, np.int16])}) @out_qs_constraint(MatchAll({'dtype': set([np.int8, np.int16])})) class SplitPow2(Pow2QuantizionHandler, SplitMixin): @classmethod def _quantize(cls, params, in_qs, stats, **kwargs): return cls._handle(params, in_qs, st...
@params_type(SplitParameters) @in_qs_constraint({'dtype': set([np.int8, np.int16])}) @out_qs_constraint(MatchAll({'dtype': set([np.int8, np.int16])})) class SplitPow2(Pow2QuantizionHandler, SplitMixin): @classmethod
def _quantize(cls, params, in_qs, stats, **kwargs): return cls._handle(params, in_qs, stats, 'symmetric', **kwargs)
@params_type(SplitParameters) @in_qs_constraint({'dtype': set([np.int8, np.int16])}) @out_qs_constraint(MatchAll({'dtype': set([np.int8, np.int16])})) class SplitPow2(Pow2QuantizionHandler, SplitMixin): @classmethod
66
64
104
66
0
mfkiwl/gap_sdk
tools/nntool/quantization/symmetric/quantizers/split_pow2.py
Python
SplitPow2
SplitPow2
30
36
30
34
b91bd75309d78a896a31d3069e6a84ff396fa14f
bigcode/the-stack
train
67be43d050a8000e05431744
train
function
def _exec(test_dir_suffix, test_bin_suffix): test_bin_path = os.path.join(os.environ['YACTFR_BINARY_DIR'], 'tests', f'tests-{test_dir_suffix}', f'test-{test_dir_suffix}-{test_bin_suffix}') assert(subprocess.call([test_bin_path]) == 0)
def _exec(test_dir_suffix, test_bin_suffix):
test_bin_path = os.path.join(os.environ['YACTFR_BINARY_DIR'], 'tests', f'tests-{test_dir_suffix}', f'test-{test_dir_suffix}-{test_bin_suffix}') assert(subprocess.call([test_bin_path]) == 0)
import pytest import os import os.path import subprocess import sys def _exec(test_dir_suffix, test_bin_suffix):
27
64
67
11
15
eepp/yactfr
tests/conftest.py
Python
_exec
_exec
8
12
8
8
c4fab6b3d9f9558b931d878064c9ed40cf5ba84a
bigcode/the-stack
train
c502bcfd85cd38d7fe16f1a4
train
function
@pytest.fixture def executor(): return _exec
@pytest.fixture def executor():
return _exec
_suffix): test_bin_path = os.path.join(os.environ['YACTFR_BINARY_DIR'], 'tests', f'tests-{test_dir_suffix}', f'test-{test_dir_suffix}-{test_bin_suffix}') assert(subprocess.call([test_bin_path]) == 0) @pytest.fixture def executor():
64
64
11
6
58
eepp/yactfr
tests/conftest.py
Python
executor
executor
15
17
15
16
76adf53ae964f3beab126c5a41f5ec390753acad
bigcode/the-stack
train
87dcc23a28a9ed1eda35d438
train
class
class RunConfigTest(unittest.TestCase): """ _RunConfigTest_ Testing the RunConfig code """ def setUp(self): """ _setUp_ """ import WMQuality.TestInit WMQuality.TestInit.deleteDatabaseAfterEveryTest("I'm Serious") self.testInit = TestInit(__file__) ...
class RunConfigTest(unittest.TestCase):
""" _RunConfigTest_ Testing the RunConfig code """ def setUp(self): """ _setUp_ """ import WMQuality.TestInit WMQuality.TestInit.deleteDatabaseAfterEveryTest("I'm Serious") self.testInit = TestInit(__file__) self.testInit.setLogging() ...
#!/usr/bin/env python """ _RunConfig_t_ Testing the RunConfig code """ import unittest import threading import logging import time import os from WMQuality.TestInit import TestInit from WMCore.DAOFactory import DAOFactory from WMCore.Database.DBFactory import DBFactory from WMCore.Configuration import loadConfigura...
132
256
30,282
8
123
hufnagel/T0
test/python/T0_t/WMBS_t/RunConfig_t/RunConfig_t.py
Python
RunConfigTest
RunConfigTest
26
1,697
26
26
ac6c029f28b87e40f5fc62c156aaed1a94f4aec6
bigcode/the-stack
train
bb9a226ce07ec8b23ba62954
train
function
def turn_right(): turn_left() turn_left() turn_left()
def turn_right():
turn_left() turn_left() turn_left()
def turn_right():
4
64
16
4
0
not-lucky/100_Days_of_Code_-_The_Complete_Python_Pro_Bootcamp_for_2022
Day 06 - Beginner - Python Functions & Karel/03_hurdle_3.py
Python
turn_right
turn_right
1
4
1
1
cb9f2503f5ec5ede335e3108916db6f7703717f9
bigcode/the-stack
train
ca0a44818d3eb884d0b9616b
train
function
def jump(): turn_left() move() turn_right() move() turn_right() move() turn_left()
def jump():
turn_left() move() turn_right() move() turn_right() move() turn_left()
def turn_right(): turn_left() turn_left() turn_left() def jump():
19
64
28
3
16
not-lucky/100_Days_of_Code_-_The_Complete_Python_Pro_Bootcamp_for_2022
Day 06 - Beginner - Python Functions & Karel/03_hurdle_3.py
Python
jump
jump
7
14
7
7
7addb650a311f6f884c4b501a90dc99bfc7c63c9
bigcode/the-stack
train
118343e68bc0c234ea25a335
train
function
@task(name='button.tasks.test') def test(param): return 'The test task executed with argument "%s" ' % param
@task(name='button.tasks.test') def test(param):
return 'The test task executed with argument "%s" ' % param
@task(name='button.tasks.temp') def temp(): humidity, temperature = Adafruit_DHT.read_retry(11, 4) if humidity and temperature: Temp.objects.create(temp=temperature, humidity=humidity) return humidity, temperature @task(name='button.tasks.test') def test(param):
64
64
28
12
51
rafen/pincho
button/tasks.py
Python
test
test
15
17
15
16
3771c9f0feb63f848d4dff020a2930f4d0c9ae90
bigcode/the-stack
train
cc36f7f68836e5d09552943d
train
function
@task(name='button.tasks.temp') def temp(): humidity, temperature = Adafruit_DHT.read_retry(11, 4) if humidity and temperature: Temp.objects.create(temp=temperature, humidity=humidity) return humidity, temperature
@task(name='button.tasks.temp') def temp():
humidity, temperature = Adafruit_DHT.read_retry(11, 4) if humidity and temperature: Temp.objects.create(temp=temperature, humidity=humidity) return humidity, temperature
from __future__ import absolute_import import Adafruit_DHT from celery import task from button.models import Temp @task(name='button.tasks.temp') def temp():
36
64
52
11
24
rafen/pincho
button/tasks.py
Python
temp
temp
7
12
7
8
473d7c8e271e33b12f2df68af7128cfeab5bd652
bigcode/the-stack
train
a1cf744817f694199cd6f06c
train
class
class AmplitudeLogger: def __init__(self, api_key, api_uri="https://api.amplitude.com/httpapi"): self.api_key = api_key self.api_uri = api_uri self.is_logging = True def turn_on_logging(self): self.is_logging = True def turn_off_logging(self): self.is_logging = Fals...
class AmplitudeLogger:
def __init__(self, api_key, api_uri="https://api.amplitude.com/httpapi"): self.api_key = api_key self.api_uri = api_uri self.is_logging = True def turn_on_logging(self): self.is_logging = True def turn_off_logging(self): self.is_logging = False def _is_None_or_...
plitudeHTTP API: # https://amplitude.zendesk.com/hc/en-us/articles/204771828 # # Convert Curl queries - such as below to - python: # https://curl.trillworks.com/ # # Example HTTP Curl Query for Amplitude: # curl --data 'api_key=SOMEIDOFAKIND' --data 'event=[{"user_id":"john_doe@gmail.com", "event_type":"watch_tu...
148
148
496
5
142
SHohentanner/amplitude-python
amplitude/__init__.py
Python
AmplitudeLogger
AmplitudeLogger
14
78
14
14
34e7cc669576fe3685191263ac6e2bc34c3580b4
bigcode/the-stack
train
f89565899628ce0d9bd02aa6
train
class
class ExpectColumnStdevToBeBetween(ColumnExpectation): """Expect the column standard deviation to be between a minimum value and a maximum value. Uses sample standard deviation (normalized by N-1). expect_column_stdev_to_be_between is a \ :func:`column_aggregate_expectation ...
class ExpectColumnStdevToBeBetween(ColumnExpectation):
"""Expect the column standard deviation to be between a minimum value and a maximum value. Uses sample standard deviation (normalized by N-1). expect_column_stdev_to_be_between is a \ :func:`column_aggregate_expectation <great_expectations.execution_engine.MetaExecut...
from typing import Dict, Optional from great_expectations.core import ExpectationConfiguration from great_expectations.execution_engine import ExecutionEngine from great_expectations.expectations.expectation import ColumnExpectation from great_expectations.expectations.util import render_evaluation_parameter_string fr...
118
256
2,051
11
107
zachlindsey/great_expectations
great_expectations/expectations/core/expect_column_stdev_to_be_between.py
Python
ExpectColumnStdevToBeBetween
ExpectColumnStdevToBeBetween
16
289
16
16
bcff4d158d8f18f8d477ddfb5cc7a3de713b9768
bigcode/the-stack
train
e55ac7a2b361ebe3d56592f0
train
class
class DQNAgent(Agent): def __init__(self, env_prototype, model_prototype, memory_prototype=None, **kwargs): super(DQNAgent, self).__init__(env_prototype, model_prototype, memory_prototype, **kwargs) self.logger.info('<===================================> DQNAgent') def _get_loss(self, experienc...
class DQNAgent(Agent):
def __init__(self, env_prototype, model_prototype, memory_prototype=None, **kwargs): super(DQNAgent, self).__init__(env_prototype, model_prototype, memory_prototype, **kwargs) self.logger.info('<===================================> DQNAgent') def _get_loss(self, experiences, logging=True): ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import torch import numpy as np from src.agents.base import Agent, adjust_learning_rate class DQNAgent(Agent):
53
256
1,914
7
45
anindex/drqn-study
src/agents/dqn.py
Python
DQNAgent
DQNAgent
11
158
11
11
11876a5681ce725d9980ecb1b09448a38607e068
bigcode/the-stack
train
f05a2de8201edf0ade12b39e
train
class
class ThreeLayerConvNetNaive1D(object): """ A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, W) consisting of N images, each transformed to an array ...
class ThreeLayerConvNetNaive1D(object):
""" A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, W) consisting of N images, each transformed to an array of W values with C input channels. ...
from builtins import object import numpy as np from nnlib.layers import * from nnlib.fast_layers import * from nnlib.layer_utils import * class ThreeLayerConvNetNaive1D(object):
42
256
1,671
11
31
adam-dziedzic/time-series-ml
cnns/nnlib/classifiers/cnn_naive_1D.py
Python
ThreeLayerConvNetNaive1D
ThreeLayerConvNetNaive1D
9
157
9
9
6c266ccfe81b7cd5b85cef2bbb1332be8826824a
bigcode/the-stack
train
b0294086f5ef600261e96ffa
train
class
class Solution: def scoreOfParentheses(self, S): if len(S) == 2: return 1 stack = [] for char in S: if char == '(': stack.append(0) elif char == ')': last_number = stack.pop() if stack: stack[-1] += ...
class Solution:
def scoreOfParentheses(self, S): if len(S) == 2: return 1 stack = [] for char in S: if char == '(': stack.append(0) elif char == ')': last_number = stack.pop() if stack: stack[-1] += max(1, 2 * last_...
# Space: O(n) # Time: O(n) class Solution:
16
64
103
3
13
lht19900714/Leetcode_Solutions
Algorithms/0856_Score_of_Parentheses/Python/Score_of_Parentheses_Solution_2.py
Python
Solution
Solution
5
20
5
5
fabf0902ce048394712df10c9fd3234ca0be0dcb
bigcode/the-stack
train
94a02719fdecd5ac04b0e648
train
class
class UsersConfig(AppConfig): name = "giftwy.users" verbose_name = "Users" def ready(self): """Override this to put in: Users system checks Users signal registration """ try: import users.signals # noqa F401 except ImportError: ...
class UsersConfig(AppConfig):
name = "giftwy.users" verbose_name = "Users" def ready(self): """Override this to put in: Users system checks Users signal registration """ try: import users.signals # noqa F401 except ImportError: pass
from django.apps import AppConfig class UsersConfig(AppConfig):
13
64
68
6
6
wangpanjun/giftwy
giftwy/users/apps.py
Python
UsersConfig
UsersConfig
4
16
4
4
6bd810c23744634954df269548084db675a5d69d
bigcode/the-stack
train
2385b0e9e2a949271c5fee85
train
function
def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'taohua.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your...
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'taohua.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
94
3
22
YellowDong/taohua
manage.py
Python
main
main
7
17
7
7
89344af6e4706da7521c59bae4ccd312d3e50389
bigcode/the-stack
train
2c64270f74cfb853755b4313
train
function
@application.route("/user-individual", methods=["POST"]) @requires_admin def create_user_individual(): try: new_user_individuals = _get_json_payload(UserIndividual) for u in new_user_individuals: _check_user_individual_valid(u) except PhenopolisException as e: application.log...
@application.route("/user-individual", methods=["POST"]) @requires_admin def create_user_individual():
try: new_user_individuals = _get_json_payload(UserIndividual) for u in new_user_individuals: _check_user_individual_valid(u) except PhenopolisException as e: application.logger.error(str(e)) return jsonify(success=False, error=str(e)), e.http_status with session_...
Individual, User, UserIndividual from views import application from views.auth import requires_admin from views.exceptions import PhenopolisException from views.helpers import _get_json_payload from views.postgres import session_scope @application.route("/user-individual", methods=["POST"]) @requires_admin def create_...
66
66
223
22
43
phenopolis/phenopolis_genomics_browser
views/user_individuals.py
Python
create_user_individual
create_user_individual
16
44
16
18
64db9d3f6da3139833305a5694050bdd06437d2e
bigcode/the-stack
train
e559fcb14f0780782999c052
train
function
@application.route("/user-individual", methods=["DELETE"]) @requires_admin def delete_user_individual(): try: user_individuals_to_be_deleted = _get_json_payload(UserIndividual) except PhenopolisException as e: return jsonify(success=False, error=str(e)), e.http_status with session_scope() a...
@application.route("/user-individual", methods=["DELETE"]) @requires_admin def delete_user_individual():
try: user_individuals_to_be_deleted = _get_json_payload(UserIndividual) except PhenopolisException as e: return jsonify(success=False, error=str(e)), e.http_status with session_scope() as db_session: request_ok = True message = "User individuals were deleted" try: ...
message = str(e) if not request_ok: return jsonify(success=False, message=message), 500 else: return jsonify(success=True, message=message), 200 @application.route("/user-individual", methods=["DELETE"]) @requires_admin def delete_user_individual():
64
64
198
22
41
phenopolis/phenopolis_genomics_browser
views/user_individuals.py
Python
delete_user_individual
delete_user_individual
47
72
47
49
72989cc6327386975c2a54d163a628232b441df7
bigcode/the-stack
train
f35f1c5ea597864383dfca59
train
function
def _check_db_integrity_user_individual(db_session: Session, user: UserIndividual): # TODO: all these checks could happen in the DB if db_session.query(User.user).filter(User.user.match(user.user)).count() != 1: raise PhenopolisException("Trying to add an entry in user_individual to a non existing user"...
def _check_db_integrity_user_individual(db_session: Session, user: UserIndividual): # TODO: all these checks could happen in the DB
if db_session.query(User.user).filter(User.user.match(user.user)).count() != 1: raise PhenopolisException("Trying to add an entry in user_individual to a non existing user", 500) if db_session.query(Individual.phenopolis_id).filter(Individual.phenopolis_id.match(user.internal_id)).count() != 1: ...
request_ok: return jsonify(success=False, message=message), 500 else: return jsonify(success=True, message=message), 200 def _check_db_integrity_user_individual(db_session: Session, user: UserIndividual): # TODO: all these checks could happen in the DB
64
64
196
32
31
phenopolis/phenopolis_genomics_browser
views/user_individuals.py
Python
_check_db_integrity_user_individual
_check_db_integrity_user_individual
75
88
75
76
5d25cfd6dcc4362b469fad19a094174fa2fbcd6d
bigcode/the-stack
train
99007835d5ecea70166f5425
train
function
def _check_user_individual_valid(new_user_individual: UserIndividual): if new_user_individual is None: raise PhenopolisException("Null user individual", 400) if new_user_individual.user is None or new_user_individual.user == "": raise PhenopolisException("Missing user", 400) if new_user_indi...
def _check_user_individual_valid(new_user_individual: UserIndividual):
if new_user_individual is None: raise PhenopolisException("Null user individual", 400) if new_user_individual.user is None or new_user_individual.user == "": raise PhenopolisException("Missing user", 400) if new_user_individual.internal_id is None or new_user_individual.internal_id == "": ...
.match(user.user)) .filter(UserIndividual.internal_id.match(user.internal_id)) .count() > 0 ): raise PhenopolisException("Trying to add an entry in user_individual that already exists", 500) def _check_user_individual_valid(new_user_individual: UserIndividual):
64
64
98
15
49
phenopolis/phenopolis_genomics_browser
views/user_individuals.py
Python
_check_user_individual_valid
_check_user_individual_valid
91
97
91
91
a572256144ca5e70130f9750d66118517204bfd7
bigcode/the-stack
train
497daef8e67bdb2d61031f98
train
function
def _run_cmd(cmd, env, cwd, allow_fail, log_fn): log_fn("---\n") try: cmd_str = " \\\n+ ".join(shellquote(arg) for arg in cmd) except TypeError: # eg: one of the elements is None raise RunCommandError("problem quoting cmd: %r" % cmd) if env: assert isinstance(env, E...
def _run_cmd(cmd, env, cwd, allow_fail, log_fn):
log_fn("---\n") try: cmd_str = " \\\n+ ".join(shellquote(arg) for arg in cmd) except TypeError: # eg: one of the elements is None raise RunCommandError("problem quoting cmd: %r" % cmd) if env: assert isinstance(env, Env) _print_env_diff(env, log_fn) ...
_stdout(msg): sys.stdout.buffer.write(msg.encode(errors="surrogateescape")) if log_file is not None: with open(log_file, "a", errors="surrogateescape") as log: def log_function(msg): log.write(msg) log_to_stdout(msg) return _run_cmd( ...
141
141
473
16
125
xujiasci/mvfst
build/fbcode_builder/getdeps/runcmd.py
Python
_run_cmd
_run_cmd
69
123
69
69
c8ed6e89082042f3b9bad30eaf9bd9cfc5e51721
bigcode/the-stack
train
230b1acb51cef2acb2bdb294
train
function
def _print_env_diff(env, log_fn): current_keys = set(os.environ.keys()) wanted_env = set(env.keys()) unset_keys = current_keys.difference(wanted_env) for k in sorted(unset_keys): log_fn("+ unset %s\n" % k) added_keys = wanted_env.difference(current_keys) for k in wanted_env.intersectio...
def _print_env_diff(env, log_fn):
current_keys = set(os.environ.keys()) wanted_env = set(env.keys()) unset_keys = current_keys.difference(wanted_env) for k in sorted(unset_keys): log_fn("+ unset %s\n" % k) added_keys = wanted_env.difference(current_keys) for k in wanted_env.intersection(current_keys): if os.env...
subprocess import sys from .envfuncs import Env from .platform import is_windows try: from shlex import quote as shellquote except ImportError: from pipes import quote as shellquote class RunCommandError(Exception): pass def _print_env_diff(env, log_fn):
64
64
196
10
53
xujiasci/mvfst
build/fbcode_builder/getdeps/runcmd.py
Python
_print_env_diff
_print_env_diff
27
46
27
27
5df3173c58a4934f40ab18368a677dc419e3d74d
bigcode/the-stack
train
ee17e141696ba10b41c33aaf
train
class
class RunCommandError(Exception): pass
class RunCommandError(Exception):
pass
print_function, unicode_literals import os import select import subprocess import sys from .envfuncs import Env from .platform import is_windows try: from shlex import quote as shellquote except ImportError: from pipes import quote as shellquote class RunCommandError(Exception):
64
64
9
6
57
xujiasci/mvfst
build/fbcode_builder/getdeps/runcmd.py
Python
RunCommandError
RunCommandError
23
24
23
23
916fc42d98c974608abfab782dd739e2f785ca1c
bigcode/the-stack
train
0fc73ced6671485ac8a0f366
train
function
def run_cmd(cmd, env=None, cwd=None, allow_fail=False, log_file=None): def log_to_stdout(msg): sys.stdout.buffer.write(msg.encode(errors="surrogateescape")) if log_file is not None: with open(log_file, "a", errors="surrogateescape") as log: def log_function(msg): lo...
def run_cmd(cmd, env=None, cwd=None, allow_fail=False, log_file=None):
def log_to_stdout(msg): sys.stdout.buffer.write(msg.encode(errors="surrogateescape")) if log_file is not None: with open(log_file, "a", errors="surrogateescape") as log: def log_function(msg): log.write(msg) log_to_stdout(msg) return _ru...
_fn("+ %s%s\\\n" % (shellquote(elem), os.pathsep)) else: log_fn("+ %s=%s \\\n" % (k, shellquote(env[k]))) def run_cmd(cmd, env=None, cwd=None, allow_fail=False, log_file=None):
63
64
148
19
44
xujiasci/mvfst
build/fbcode_builder/getdeps/runcmd.py
Python
run_cmd
run_cmd
49
66
49
49
9840de0ee5b9a116a281d047b22f394c501cdfa5
bigcode/the-stack
train
5a7feb6b62af0a06ebc89041
train
function
def display_results(image_paths, probs): '''Displays the classification results given the class probability for each image''' # Get a list of ImageNet class labels with open('imagenet-classes.txt', 'rb') as infile: class_labels = map(str.strip, infile.readlines()) # Pick the class with the highe...
def display_results(image_paths, probs):
'''Displays the classification results given the class probability for each image''' # Get a list of ImageNet class labels with open('imagenet-classes.txt', 'rb') as infile: class_labels = map(str.strip, infile.readlines()) # Pick the class with the highest confidence for each image class_in...
#!/usr/bin/env python import argparse import numpy as np import tensorflow as tf import os.path as osp import models import dataset def display_results(image_paths, probs):
39
64
200
8
30
melody-rain/caffe-tensorflow
examples/imagenet/classify_mobilenet.py
Python
display_results
display_results
11
25
11
11
c3e11256c95659c88a9b6fa573d5a1fe90036203
bigcode/the-stack
train
6d23a769f1e91876de3cfb67
train
function
def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('model_path', help='Converted parameters for the mobilenet model') parser.add_argument('image_paths', nargs='+', help='One or more images to classify') args = parser.parse_args() # Classify the image classi...
def main(): # Parse arguments
parser = argparse.ArgumentParser() parser.add_argument('model_path', help='Converted parameters for the mobilenet model') parser.add_argument('image_paths', nargs='+', help='One or more images to classify') args = parser.parse_args() # Classify the image classify(args.model_path, args.image_pat...
h.run(net.get_output(), feed_dict={input_node: input_images}) display_results([image_paths[i] for i in indices], probs) # Stop the worker threads coordinator.request_stop() coordinator.join(threads, stop_grace_period_secs=2) def main(): # Parse arguments
64
64
77
8
56
melody-rain/caffe-tensorflow
examples/imagenet/classify_mobilenet.py
Python
main
main
66
74
66
67
559e64dbe69c3e609f225c9d2a76b899af1aa0d0
bigcode/the-stack
train
b49f5d754febc36d0e3bb69e
train
function
def classify(model_data_path, image_paths): '''Classify the given images using mobilenet.''' # Get the data specifications for the mobilenet model spec = models.get_data_spec(model_class=models.MOBILENET) # Create a placeholder for the input image input_node = tf.placeholder(tf.float32, ...
def classify(model_data_path, image_paths):
'''Classify the given images using mobilenet.''' # Get the data specifications for the mobilenet model spec = models.get_data_spec(model_class=models.MOBILENET) # Create a placeholder for the input image input_node = tf.placeholder(tf.float32, shape=(None, spec.crop...
print('-' * 70) for img_idx, image_path in enumerate(image_paths): img_name = osp.basename(image_path) class_name = class_labels[class_indices[img_idx]] confidence = round(probs[img_idx, class_indices[img_idx]] * 100, 2) print('{:20} {:30} {} %'.format(img_name, class_name, confiden...
93
93
311
9
84
melody-rain/caffe-tensorflow
examples/imagenet/classify_mobilenet.py
Python
classify
classify
28
64
28
28
c068d2b9a5b16db162f262f3e8df68cbc82a3e48
bigcode/the-stack
train
1393a2ef851966541fd479d3
train
class
class OxCGRTData(CleaningBase): """ Data cleaning of OxCGRT dataset. """ COL_DICT = { "GovernmentResponseIndexForDisplay": "Government response index", "ContainmentHealthIndexForDisplay": "Containment and health index", "StringencyIndexForDisplay": "Stringency index", "Ec...
class OxCGRTData(CleaningBase):
""" Data cleaning of OxCGRT dataset. """ COL_DICT = { "GovernmentResponseIndexForDisplay": "Government response index", "ContainmentHealthIndexForDisplay": "Containment and health index", "StringencyIndexForDisplay": "Stringency index", "EconomicSupportIndexForDisplay": "...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd from covsirphy.cleaning.cbase import CleaningBase class OxCGRTData(CleaningBase):
41
233
778
10
30
skelwadkar/COVID-19_project
covsirphy/cleaning/oxcgrt.py
Python
OxCGRTData
OxCGRTData
8
88
8
8
7338fa86e6e8920f2e249ea2a732a6554275d105
bigcode/the-stack
train
8627dda27e9bc98dcf9e0b3f
train
class
class FeatureStatisticsResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribu...
class FeatureStatisticsResponse(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ Seldon Deploy API API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501 OpenAPI spec version: v1alpha1 Contact: hello@seldon.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint...
99
256
1,376
6
92
SachinVarghese/seldon-deploy-sdk
python/seldon_deploy_sdk/models/feature_statistics_response.py
Python
FeatureStatisticsResponse
FeatureStatisticsResponse
20
225
20
20
cef28f960f01e9cb43524edab68e696b1734651b
bigcode/the-stack
train
2a8cd1866bec94c1ef910c96
train
function
def glInitBlendLogicOpEXT(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
def glInitBlendLogicOpEXT():
'''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.EXT.blend_logic_op import * from OpenGL.raw.GL.EXT.blend_logic_op import _EXTENSION_NAME def glInitBlendLogicOpEXT():
64
64
39
8
55
JE-Chen/je_old_repo
OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/EXT/blend_logic_op.py
Python
glInitBlendLogicOpEXT
glInitBlendLogicOpEXT
26
29
26
26
ddf22e87675468e7bbb1de26700da298cbffde21
bigcode/the-stack
train
fc8d62b5f0e49d06a2f311e4
train
class
class AiogramMainRouter(BaseMainRouter, AiogramRouter): def __init__(self, token: str): super().__init__(token=token) bot = Bot(token=token) self.dp = Dispatcher(bot) self.inject_values = {Bot: bot, Dispatcher: self.dp} def install( self, *, storage: Optional[BaseStorage...
class AiogramMainRouter(BaseMainRouter, AiogramRouter):
def __init__(self, token: str): super().__init__(token=token) bot = Bot(token=token) self.dp = Dispatcher(bot) self.inject_values = {Bot: bot, Dispatcher: self.dp} def install( self, *, storage: Optional[BaseStorage] = None, default_state_name: Optional[str] = None )...
import redis logger = getLogger(__name__) class AiogramRouter(BaseRouter): def __init__(self): super().__init__() self.on_state = AiogramStateHandler(self._state_storage) self.on = AiogramHandler(self._state_storage) class AiogramMainRouter(BaseMainRouter, AiogramRouter):
68
68
227
13
55
Bloodielie/state_manager
state_manager/routes/aiogram/complete.py
Python
AiogramMainRouter
AiogramMainRouter
24
49
24
24
5a8aa7247378fd5e7c81efb6e4b7eca8a962de6a
bigcode/the-stack
train
158143a7c1b9437f15ee40e5
train
class
class AiogramRouter(BaseRouter): def __init__(self): super().__init__() self.on_state = AiogramStateHandler(self._state_storage) self.on = AiogramHandler(self._state_storage)
class AiogramRouter(BaseRouter):
def __init__(self): super().__init__() self.on_state = AiogramStateHandler(self._state_storage) self.on = AiogramHandler(self._state_storage)
Processor from state_manager.handlers.aiogram import AiogramStateHandler, AiogramHandler from state_manager.routes.base.complete import BaseRouter, BaseMainRouter from state_manager.storage_settings import StorageSettings from state_manager.storages import redis logger = getLogger(__name__) class AiogramRouter(BaseRou...
64
64
45
7
57
Bloodielie/state_manager
state_manager/routes/aiogram/complete.py
Python
AiogramRouter
AiogramRouter
17
21
17
17
ff054336e828419b402dc996fb71f9d152d8407b
bigcode/the-stack
train
38495e8643ef289cb06417ea
train
function
def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dekanat_4.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on y...
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dekanat_4.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPA...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
96
3
22
H0oxy/dekanat-4
dekanat_4/manage.py
Python
main
main
7
17
7
7
a2e93a57b3d5e3b857b206b4008f19a1e34d4efc
bigcode/the-stack
train
a52791fe2c3de8afaa70ee48
train
function
async def _async_update_listener( hass: HomeAssistant, entry: config_entries.ConfigEntry ): """Handle options update.""" await hass.config_entries.async_reload(entry.entry_id)
async def _async_update_listener( hass: HomeAssistant, entry: config_entries.ConfigEntry ):
"""Handle options update.""" await hass.config_entries.async_reload(entry.entry_id)
= entry.add_update_listener(_async_update_listener) hass_isy_data[UNDO_UPDATE_LISTENER] = undo_listener # Register Integration-wide Services: async_setup_services(hass) return True async def _async_update_listener( hass: HomeAssistant, entry: config_entries.ConfigEntry ):
64
64
38
21
42
edofullin/core
homeassistant/components/isy994/__init__.py
Python
_async_update_listener
_async_update_listener
202
206
202
204
f2f62e93b701f8d6591f9d7e7f9c10a5589a696e
bigcode/the-stack
train
aafeeeadd0146b90c8293af1
train
function
async def async_unload_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool: """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS...
async def async_unload_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool:
"""Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ] ) ) hass_isy_data = hass.data[DOMAIN][entry.entry_id] isy = has...
.configuration["uuid"])}, manufacturer=MANUFACTURER, name=isy.configuration["name"], model=isy.configuration["model"], sw_version=isy.configuration["firmware"], ) async def async_unload_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool:
64
64
198
24
40
edofullin/core
homeassistant/components/isy994/__init__.py
Python
async_unload_entry
async_unload_entry
244
275
244
246
9a16b22f596f3d5a8444dd6f70670e41cda759b1
bigcode/the-stack
train
3978c72091d8e8fc4cdbe48a
train
function
@callback def _async_import_options_from_data_if_missing( hass: HomeAssistant, entry: config_entries.ConfigEntry ): options = dict(entry.options) modified = False for importable_option in [ CONF_IGNORE_STRING, CONF_SENSOR_STRING, CONF_RESTORE_LIGHT_STATE, ]: if import...
@callback def _async_import_options_from_data_if_missing( hass: HomeAssistant, entry: config_entries.ConfigEntry ):
options = dict(entry.options) modified = False for importable_option in [ CONF_IGNORE_STRING, CONF_SENSOR_STRING, CONF_RESTORE_LIGHT_STATE, ]: if importable_option not in entry.options and importable_option in entry.data: options[importable_option] = entry.dat...
def _async_update_listener( hass: HomeAssistant, entry: config_entries.ConfigEntry ): """Handle options update.""" await hass.config_entries.async_reload(entry.entry_id) @callback def _async_import_options_from_data_if_missing( hass: HomeAssistant, entry: config_entries.ConfigEntry ):
64
64
120
27
37
edofullin/core
homeassistant/components/isy994/__init__.py
Python
_async_import_options_from_data_if_missing
_async_import_options_from_data_if_missing
209
225
209
212
044af119bcade0f9eac35e66603d4f8b82c0c1e6
bigcode/the-stack
train
dc80aeca6a83061161120d20
train
function
async def async_setup_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool: """Set up the ISY 994 integration.""" # As there currently is no way to import options from yaml # when setting up a config entry, we fallback to adding # the options to the config entry and pull them out ...
async def async_setup_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool:
"""Set up the ISY 994 integration.""" # As there currently is no way to import options from yaml # when setting up a config entry, we fallback to adding # the options to the config entry and pull them out here if # they are missing from the options _async_import_options_from_data_if_missing(hass...
async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the isy994 integration from YAML.""" isy_config: ConfigType | None = config.get(DOMAIN) hass.data.setdefault(DOMAIN, {}) if not isy_config: return True # Only import if we haven't before. config_entry = _async_fin...
236
236
787
23
212
edofullin/core
homeassistant/components/isy994/__init__.py
Python
async_setup_entry
async_setup_entry
101
199
101
103
02af935bfe1b48f385382e3a6563a4e179383394
bigcode/the-stack
train
1f4cf593f45a8212a46bab97
train
function
@callback def _async_find_matching_config_entry(hass): for entry in hass.config_entries.async_entries(DOMAIN): if entry.source == config_entries.SOURCE_IMPORT: return entry
@callback def _async_find_matching_config_entry(hass):
for entry in hass.config_entries.async_entries(DOMAIN): if entry.source == config_entries.SOURCE_IMPORT: return entry
data=dict(isy_config), ) ) return True # Update the entry based on the YAML configuration, in case it changed. hass.config_entries.async_update_entry(config_entry, data=dict(isy_config)) return True @callback def _async_find_matching_config_entry(hass):
64
64
41
13
50
edofullin/core
homeassistant/components/isy994/__init__.py
Python
_async_find_matching_config_entry
_async_find_matching_config_entry
94
98
94
95
33674fff8cde38b6b2d473f66a3597316af566c7
bigcode/the-stack
train
54f8fea1fbc54d64c69a043a
train
function
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the isy994 integration from YAML.""" isy_config: ConfigType | None = config.get(DOMAIN) hass.data.setdefault(DOMAIN, {}) if not isy_config: return True # Only import if we haven't before. config_entry = _...
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the isy994 integration from YAML.""" isy_config: ConfigType | None = config.get(DOMAIN) hass.data.setdefault(DOMAIN, {}) if not isy_config: return True # Only import if we haven't before. config_entry = _async_find_matching_config_entry(hass) if not config_entry: ...
_SENSOR_STRING ): cv.string, vol.Required( CONF_RESTORE_LIGHT_STATE, default=DEFAULT_RESTORE_LIGHT_STATE ): bool, } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
64
64
174
18
46
edofullin/core
homeassistant/components/isy994/__init__.py
Python
async_setup
async_setup
69
91
69
69
deafcf567ebc789036d2bb953bf07a6d05e9f799
bigcode/the-stack
train
c8e43b6e903ae8b8ceb35f0d
train
function
async def _async_get_or_create_isy_device_in_registry( hass: HomeAssistant, entry: config_entries.ConfigEntry, isy ) -> None: device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, isy...
async def _async_get_or_create_isy_device_in_registry( hass: HomeAssistant, entry: config_entries.ConfigEntry, isy ) -> None:
device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, isy.configuration["uuid"])}, identifiers={(DOMAIN, isy.configuration["uuid"])}, manufacturer=MANUFACTURER, na...
] = entry.data[importable_option] modified = True if modified: hass.config_entries.async_update_entry(entry, options=options) async def _async_get_or_create_isy_device_in_registry( hass: HomeAssistant, entry: config_entries.ConfigEntry, isy ) -> None:
64
64
125
33
31
edofullin/core
homeassistant/components/isy994/__init__.py
Python
_async_get_or_create_isy_device_in_registry
_async_get_or_create_isy_device_in_registry
228
241
228
230
04352a5ff4257ae3b5fa10e3945fed894528ea12
bigcode/the-stack
train
25364ba12838b412fb7e2883
train
class
class PlantumlTest_fenced(PlantumlTest): def setUp(self): super(PlantumlTest_fenced, self).setUp() # Setup testing with backticks fenced block delimiter self.text_builder = MarkdownBuilder() def test_tildes(self): """ Test correct parsing with tilde fenced block delimit...
class PlantumlTest_fenced(PlantumlTest):
def setUp(self): super(PlantumlTest_fenced, self).setUp() # Setup testing with backticks fenced block delimiter self.text_builder = MarkdownBuilder() def test_tildes(self): """ Test correct parsing with tilde fenced block delimiter """ self.text_builder =...
import unittest from test.markdown_builder import MarkdownBuilder from test.test_plantuml import PlantumlTest class PlantumlTest_fenced(PlantumlTest):
34
113
378
11
22
freezed/plantuml-markdown
test/test_plantuml_fenced.py
Python
PlantumlTest_fenced
PlantumlTest_fenced
7
44
7
8
1cd2eecfad2218a24e92227d539425d4816cccae
bigcode/the-stack
train
4b9afd62473f2ae9dec7b63c
train
function
def annotate(): ogfiles = [open('etl/data/webchildsampling/loaded/DF_annotations.csv'), open('etl/data/webchildsampling/loaded/MG_annotations.csv')] newfiles = [open('etl/data/webchildsampling/loaded/DF_annotations_anlys.csv',mode='w'), open('etl/data/webchildsampling/loaded/MG_annotations_anlys.csv', mode...
def annotate():
ogfiles = [open('etl/data/webchildsampling/loaded/DF_annotations.csv'), open('etl/data/webchildsampling/loaded/MG_annotations.csv')] newfiles = [open('etl/data/webchildsampling/loaded/DF_annotations_anlys.csv',mode='w'), open('etl/data/webchildsampling/loaded/MG_annotations_anlys.csv', mode='w')] tran...
import csv try: import mowgli_etl except ImportError: import os.path import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))) from mowgli_etl.pipeline.web_child.web_child_transformer import WebChildTransformer from mowgli_etl.model.kg_edge import KgEdge d...
82
171
573
3
78
tetherless-world/mowgli
mowgli_etl/pipeline/web_child/web_child_annotate.py
Python
annotate
annotate
15
74
15
15
7381dc6b5fdf47734f9ed885e150edd1b916389f
bigcode/the-stack
train
d4d1891c82689d607146febb
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "poll", sa.Column( "european_date_format", sa.Boolean(), server_default="false", nullable=False ), ) op.alter_column( "poll", "allow_new_options", exist...
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.add_column( "poll", sa.Column( "european_date_format", sa.Boolean(), server_default="false", nullable=False ), ) op.alter_column( "poll", "allow_new_options", existing_type=sa.BOOLEAN(), server_default=None, existing_nullable=Fal...
as sa # revision identifiers, used by Alembic. revision = "381ef6581a03" down_revision = "1a668c8e3285" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
189
18
45
tigerdar004/RweddingPoll
migrations/versions/2019_06_28_381ef6581a03_dateformat.py
Python
upgrade
upgrade
19
51
19
20
aa7d4e9e36094cca511bd930e37f5675e3dafe27
bigcode/the-stack
train
89edd8fe0bea41621094eeee
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("poll_option", "is_date") op.alter_column( "poll", "show_percentage", existing_type=sa.BOOLEAN(), server_default=sa.text("true"), existing_nullable=False, ) op.alter_...
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_column("poll_option", "is_date") op.alter_column( "poll", "show_percentage", existing_type=sa.BOOLEAN(), server_default=sa.text("true"), existing_nullable=False, ) op.alter_column( "poll", "deleted", existing_type=sa.BOOLEAN(), ...
existing_nullable=False, ) op.add_column( "poll_option", sa.Column("is_date", sa.Boolean(), server_default="False", nullable=False), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
161
18
45
tigerdar004/RweddingPoll
migrations/versions/2019_06_28_381ef6581a03_dateformat.py
Python
downgrade
downgrade
55
79
55
56
f4423a6535d63e081c68f2f71d5c976c81dc6a45
bigcode/the-stack
train
3055b72c298891c7f8726c35
train
function
def FoldScaleAxis(): """Fold the scaling of axis into weights of conv2d/dense. This pass will invoke both forward and backward scale folding. Returns ------- ret : tvm.transform.Pass The registered pass to fold expressions. Note ---- Internally, we will call backward_fold_scale...
def FoldScaleAxis():
"""Fold the scaling of axis into weights of conv2d/dense. This pass will invoke both forward and backward scale folding. Returns ------- ret : tvm.transform.Pass The registered pass to fold expressions. Note ---- Internally, we will call backward_fold_scale_axis before using ...
pass class should be created through `function_pass`. """ def InferType(): """Infer the type of an expr. Returns ------- ret : tvm.transform.Pass The registered type inference pass. """ return _ffi_api.InferType() def FoldScaleAxis():
64
64
105
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
FoldScaleAxis
FoldScaleAxis
102
117
102
102
a51544a42cad1fd1a5d1633d3d9f07b10a236081
bigcode/the-stack
train
92505a4a3cae60c6d32785f7
train
function
def to_cps(func, mod=None): """ Turn expression into CPS expression. Every intermediate compute will be passed to a continuation. Parameters ---------- func: tvm.relay.Function The input function. mod: Optional[tvm.IRModule] The global module. Returns ------- ...
def to_cps(func, mod=None):
""" Turn expression into CPS expression. Every intermediate compute will be passed to a continuation. Parameters ---------- func: tvm.relay.Function The input function. mod: Optional[tvm.IRModule] The global module. Returns ------- result: tvm.relay.Function ...
lay.Expr The transformed expression. """ if mode == 'first_order': return _ffi_api.first_order_gradient(expr, mod) if mode == 'higher_order': return _ffi_api.gradient(expr, mod) raise Exception('unknown mode') def to_cps(func, mod=None):
64
64
113
9
55
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
to_cps
to_cps
740
760
740
740
12eeef290d330334ac5e022aff4ca94ddedefda8
bigcode/the-stack
train
99573f9a925c3ef3820dab9a
train
function
def FuseOps(fuse_opt_level=-1): """Fuse operators in an expr to a larger operator according to some rules. Parameters ---------- fuse_opt_level : int The level of fuse optimization. -1 indicates that the level will be inferred from pass context. Returns ------- ret : tvm.tr...
def FuseOps(fuse_opt_level=-1):
"""Fuse operators in an expr to a larger operator according to some rules. Parameters ---------- fuse_opt_level : int The level of fuse optimization. -1 indicates that the level will be inferred from pass context. Returns ------- ret : tvm.transform.Pass The registe...
ffi_api.LazyGradientInit() def FoldConstant(): """Fold the constant expressions in a Relay program. Returns ------- ret : tvm.transform.Pass The registered pass for constant folding. """ return _ffi_api.FoldConstant() def FuseOps(fuse_opt_level=-1):
64
64
96
10
54
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
FuseOps
FuseOps
246
260
246
246
104881c5300d4f8139240d7a3f94ee9211edca45
bigcode/the-stack
train
edd79e2d04848e01d0e95c8a
train
function
def Legalize(legalize_map_attr_name="FTVMLegalize"): """Legalizes an expression with another expression. This pass can be used to replace an expr with another expr for target dependent optimizations. For example, one expr, though semnatically equivalent to the other, can have better performance on a tar...
def Legalize(legalize_map_attr_name="FTVMLegalize"):
"""Legalizes an expression with another expression. This pass can be used to replace an expr with another expr for target dependent optimizations. For example, one expr, though semnatically equivalent to the other, can have better performance on a target. This pass can be used to legalize the expr i...
the first item in the list specifies the data layout and the second specifies the kernel layout. Returns ------- pass: FunctionPass The pass. """ return _ffi_api.ConvertLayout(desired_layouts) def Legalize(legalize_map_attr_name="FTVMLegalize"):
64
64
158
15
49
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
Legalize
Legalize
417
434
417
417
054d64ebbcf861a24ed0106f386665c1ae4ae3dd
bigcode/the-stack
train
ea73b73b61b002a004dd0c4f
train
function
def DenseToSparse(weight_name, weight_shape): """ Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense``` This pass is used in ```data_dep_optimization.bsr_dense``` Parameters of this pass is generated by ```analysis.sparse_dense.process_params``` Parameters ---------- weight_na...
def DenseToSparse(weight_name, weight_shape):
""" Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense``` This pass is used in ```data_dep_optimization.bsr_dense``` Parameters of this pass is generated by ```analysis.sparse_dense.process_params``` Parameters ---------- weight_name: Array[String] Names of weights which...
new_shape = list(ty.shape) new_shape[change_batch.data[var]] = change_batch.batch_size return relay.Var(var.name_hint, relay.TensorType(new_shape, ty.dtype)) return var return ChangeBatchMutator().visit(func) def DenseToSparse(weight_name, weight_shape):
64
64
140
10
54
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
DenseToSparse
DenseToSparse
948
967
948
948
e6fd962ffc3ac23b39c86dd6c8e5272aa10b8792
bigcode/the-stack
train
98025ace545199335080ba30
train
function
def FastMath(): """ Converts the expensive non linear functions to their fast but approximate counterparts. Returns ------- ret: tvm.transform.Pass The registered pass to perform fast math operations. """ return _ffi_api.FastMath()
def FastMath():
""" Converts the expensive non linear functions to their fast but approximate counterparts. Returns ------- ret: tvm.transform.Pass The registered pass to perform fast math operations. """ return _ffi_api.FastMath()
data-flow graph for inference phase. An simplified expression which is semantically equal to the input expression will be returned. Returns ------- ret: tvm.transform.Pass The registered pass to perform operator simplification. """ return _ffi_api.SimplifyInference() def FastMath():
64
64
52
4
60
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
FastMath
FastMath
182
190
182
182
066cdd17ab6ea59657706a3d4958000b4dc4be3e
bigcode/the-stack
train
95b55fe2b08d5b09fa31c38b
train
function
def DeadCodeElimination(inline_once=False): """Remove expressions that do not have any users (dead code). Parameters ---------- inline_once: Optional[Bool] Whether to inline binding that occurs only once. Returns ------- ret: tvm.transform.Pass The registered pass that elim...
def DeadCodeElimination(inline_once=False):
"""Remove expressions that do not have any users (dead code). Parameters ---------- inline_once: Optional[Bool] Whether to inline binding that occurs only once. Returns ------- ret: tvm.transform.Pass The registered pass that eliminates the dead code in a Relay program. ...
can simplify followed analysis, e.g. expanding bias_add to expand_dims and broadcast_add. Returns ------- ret: tvm.transform.Pass The registered pass performing the canonicalization. """ return _ffi_api.CanonicalizeOps() def DeadCodeElimination(inline_once=False):
64
64
90
10
54
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
DeadCodeElimination
DeadCodeElimination
206
219
206
206
a6a4e79333ac2af814ba0e7e0cd524e707679d97
bigcode/the-stack
train
735f68bc1bd46565eada1230
train
function
def un_cps(func): """ Turn an cps function into a Function without the continuation argument. Note that this will not give the exact same interface as before cps: If the input/output is higher order, they will still be in cps form. Parameters ---------- func: tvm.relay.Function T...
def un_cps(func):
""" Turn an cps function into a Function without the continuation argument. Note that this will not give the exact same interface as before cps: If the input/output is higher order, they will still be in cps form. Parameters ---------- func: tvm.relay.Function The input function ...
Module] The global module. Returns ------- result: tvm.relay.Function The output function. """ use_mod = mod if mod is not None else tvm.ir.IRModule() return _ffi_api.to_cps(func, use_mod) def un_cps(func):
64
64
103
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
un_cps
un_cps
763
780
763
763
828ba3fbaee898ce518ccc91099d09d1fa60cc41
bigcode/the-stack
train