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
4f5db4e1b00a34fd3f0406c3
train
function
def abc(): return dict(message='')
def abc():
return dict(message='')
""" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service() def abc():
64
64
8
3
61
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
abc
abc
180
181
180
180
6631fa7d51932f316f5c4bc675ce573aed89f5f8
bigcode/the-stack
train
808e2ac55db0722c5ba34578
train
function
def view_prob(): idss=request.get_vars prob=db(db.Problems.id==idss).select() return idss
def view_prob():
idss=request.get_vars prob=db(db.Problems.id==idss).select() return idss
onvalidation=validate response.flash='Thank You, Your Solution Has Been Successfully Submitted' redirect(URL(r=request,f='index')) elif form.errors: response.flash='Please Check The Form Again' else: response.flash='Upload Your Solution' return dict(form=form) def view_prob()...
64
64
29
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
view_prob
view_prob
58
61
58
58
9d1ed44270bbb97c9b1f53f8c67e28d8a04e51d9
bigcode/the-stack
train
071a423f12591c7679828a0a
train
function
def call(): """ exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service()
def call():
""" exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service()
app]/appadmin/manage/auth to allow administrator to manage users """ return dict(form=auth()) @cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db) def call():
64
64
64
3
61
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
call
call
171
178
171
171
e1f74776c22fdee538bbbf693edf390bcf8d4d36
bigcode/the-stack
train
1284dfa71d9e45df09183521
train
function
def superadmin1(): return dict(form)
def superadmin1():
return dict(form)
_classes = dict(csv=True, json=True, html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) sol = SQLFORM.grid(db.Solutions, showbuttontext=False,user_signature=False) return dict(sol=sol) def superadmin1():
64
64
10
5
59
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
superadmin1
superadmin1
210
211
210
210
3f8c28aa2a793c5ed321010e931d1e7ece667168
bigcode/the-stack
train
a94353ff71526e4b5a434f4e
train
function
def join(uid): v=db(db.Slck.user_id==uid).select(db.Slck.slack_pass) sc = SlackClient(v) x = sc.api_call("channels.join",name="MyChannel") x=x["channel"]["id"] y = db(db.Col).select(db.Col.ch_id) if y==None: db.Col.insert(ch_id=x)
def join(uid):
v=db(db.Slck.user_id==uid).select(db.Slck.slack_pass) sc = SlackClient(v) x = sc.api_call("channels.join",name="MyChannel") x=x["channel"]["id"] y = db(db.Col).select(db.Col.ch_id) if y==None: db.Col.insert(ch_id=x)
the problem givers. Courses recommended after analysis of archived data') def Contact_us(): return dict(message='I am working') def collaboration(): return locals() def console(): return locals() # -*- coding: utf-8 -*- # try something like from slackclient import SlackClient def join(uid):
64
64
82
4
59
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
join
join
226
233
226
226
c7ac3e8d7abb9850c48108a503c3a6c9f02d6c70
bigcode/the-stack
train
28be6a3d5f75c65b8edc7278
train
function
def relatedsolution(): pp=db(request.args[0]==db.Problems.id).select() return locals()
def relatedsolution():
pp=db(request.args[0]==db.Problems.id).select() return locals()
knitishnitj@gmail.com' or mail.email=='setiadeepanshu@gmail.com': redirect(URL(r=request,f='browse_prob_admin')) else: redirect(URL(r=request,f='Browse_problem')) form=SQLFORM(db.Locate) return dict(form=form) def relatedsolution():
64
64
23
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
relatedsolution
relatedsolution
140
142
140
140
fee61b0c32a07e50d53a0b66f5d8162c6c8d8d01
bigcode/the-stack
train
88ea53d51a167476aa472fa2
train
function
def About_us(): return dict(message='A digital web tool for gathering local relevant problems by analysis of problems posted directly or on social networking sites (Hash Tag) and then categorizing them in various domains i.e., departments etc. Problems reported to nearby institutes and are taken by department heads...
def About_us():
return dict(message='A digital web tool for gathering local relevant problems by analysis of problems posted directly or on social networking sites (Hash Tag) and then categorizing them in various domains i.e., departments etc. Problems reported to nearby institutes and are taken by department heads. After approval...
html=False, tsv=False, xml=False, csv_with_hidden_cols=False, tsv_with_hidden_cols=False) sol = SQLFORM.grid(db.Solutions, showbuttontext=False,user_signature=False) return dict(sol=sol) def superadmin1(): return dict(form) def About_us():
64
64
96
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
About_us
About_us
213
214
213
213
fe2844a9fe6a81b500622f8f3b7c62076a9a73b6
bigcode/the-stack
train
7e674617034a9ec5f92759cf
train
function
def superadmin(): form1=SQLFORM(db.Colleges) if form1.process().accepted: response.flash='Thank You, New College Has Been Successfully Added' redirect(URL(r=request,f='superadmin')) elif form1.errors: response.flash='Please Check The Form Again' else: response.flash='Add ...
def superadmin():
form1=SQLFORM(db.Colleges) if form1.process().accepted: response.flash='Thank You, New College Has Been Successfully Added' redirect(URL(r=request,f='superadmin')) elif form1.errors: response.flash='Please Check The Form Again' else: response.flash='Add New College Here' ...
http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service() def abc(): return dict(message='') def superadmin():
63
64
82
4
60
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
superadmin
superadmin
183
192
183
183
9869a7c3ae1662060679fa60ebe31e0f47e36cc1
bigcode/the-stack
train
8ab8c6e91e9150e58cb97e78
train
function
def stackrank(): #r_tb=db().select(db.Rankings) return locals()
def stackrank(): #r_tb=db().select(db.Rankings)
return locals()
local_import('sendMail') chk=local_import('verifyMail') city=local_import('states') rnk=local_import('ranking') #!/usr/bin/env python # -*- coding: utf-8 -*- from gluon import * def stackrank(): #r_tb=db().select(db.Rankings)
64
64
20
16
48
SETIADEEPANSHU/iSahayog
applications/UGC/controllers/default.py
Python
stackrank
stackrank
20
22
20
21
f68321ffb4a5d9b6aafaadf6bf12c359693509ce
bigcode/the-stack
train
5fe9e105123919727ccc8c4b
train
class
class FilterBank(mir3.module.Module): """Calculates energy through a triangular filter bank""" def get_help(self): return """Bandwise energy of each frame of a spectrogram""" def build_arguments(self, parser): parser.add_argument('central_frequencies', type=float, help="""c...
class FilterBank(mir3.module.Module):
"""Calculates energy through a triangular filter bank""" def get_help(self): return """Bandwise energy of each frame of a spectrogram""" def build_arguments(self, parser): parser.add_argument('central_frequencies', type=float, help="""central filter frequencies""", nargs="+...
import argparse import numpy import mir3.data.feature_track as track import mir3.data.spectrogram as spectrogram import mir3.module class FilterBank(mir3.module.Module):
40
126
421
9
30
pymir3/pymir3
mir3/modules/features/filterbank.py
Python
FilterBank
FilterBank
8
59
8
8
15b6b37e32a2889ccad44f0e61469268d5b3b25f
bigcode/the-stack
train
9cb00c0a879d06c51a9c0329
train
class
class IndonesianDataset(BaseDataset): def __init__(self, parent_directory, extension, csv_file): super().__init__(parent_directory, extension) try: self.csv_file = pd.read_csv(csv_file) self.csv_file.drop_duplicates(subset=['NAMA'], inplace=True) except FileNotFoundEr...
class IndonesianDataset(BaseDataset):
def __init__(self, parent_directory, extension, csv_file): super().__init__(parent_directory, extension) try: self.csv_file = pd.read_csv(csv_file) self.csv_file.drop_duplicates(subset=['NAMA'], inplace=True) except FileNotFoundError: print(f'Csv file not ...
from pathlib import Path from torchvision import transforms from torchetl.base.dataset import BaseDataset from torchetl.etl import Extract import pandas as pd import pdb from collections import namedtuple import numpy as np import re class IndonesianDataset(BaseDataset):
57
82
275
6
50
amajidsinar/seer
seer/datasets/indonesian_dataset.py
Python
IndonesianDataset
IndonesianDataset
11
47
11
11
ae42b4a5757dac4c8db04f003989f896d19571b8
bigcode/the-stack
train
2d82a9fa849327f1791feb38
train
class
class TFRecordReaderTest(TFCompressionTestCase): def setUp(self): super(TFRecordReaderTest, self).setUp() @test_util.run_deprecated_v1 def testOneEpoch(self): files = self._CreateFiles() reader = io_ops.TFRecordReader(name="test_reader") queue = data_flow_ops.FIFOQueue(99, [dtypes.strin...
class TFRecordReaderTest(TFCompressionTestCase):
def setUp(self): super(TFRecordReaderTest, self).setUp() @test_util.run_deprecated_v1 def testOneEpoch(self): files = self._CreateFiles() reader = io_ops.TFRecordReader(name="test_reader") queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) key, value = reader.read(queue) ...
test_util.run_deprecated_v1 def testOneEpochWithHopBytes(self): for num_overlapped_records in [0, 2]: files = self._CreateOverlappedRecordFiles(num_overlapped_records) self._TestOneEpochWithHopBytes(files, num_overlapped_records) @test_util.run_deprecated_v1 def testGzipOneEpochWithHopByte...
236
237
792
11
225
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
TFRecordReaderTest
TFRecordReaderTest
623
707
623
624
6d02aac6e57d338c5b7ca61a171bba506e1e3c99
bigcode/the-stack
train
b952d97d7add01980a99d066
train
class
class WholeFileReaderTest(test.TestCase): def setUp(self): super(WholeFileReaderTest, self).setUp() self._filenames = [ os.path.join(self.get_temp_dir(), "whole_file.%d.txt" % i) for i in range(3) ] self._content = [b"One\na\nb\n", b"Two\nC\nD", b"Three x, y, z"] for fn, ...
class WholeFileReaderTest(test.TestCase):
def setUp(self): super(WholeFileReaderTest, self).setUp() self._filenames = [ os.path.join(self.get_temp_dir(), "whole_file.%d.txt" % i) for i in range(3) ] self._content = [b"One\na\nb\n", b"Two\nC\nD", b"Three x, y, z"] for fn, c in zip(self._filenames, self._content): ...
X") self.assertLess(0, self.evaluate(queued_length)) self.assertAllEqual(1, self.evaluate(produced)) self._ExpectRead(key, value, b"Y") self.assertLess(0, self.evaluate(work_completed)) self.assertAllEqual(2, self.evaluate(produced)) self.evaluate(reader.reset()) self.assertAllEqu...
160
161
539
9
151
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
WholeFileReaderTest
WholeFileReaderTest
287
342
287
288
9b06f36d79394b3d651c161789992a8f01537ce8
bigcode/the-stack
train
a108133c440576c6d776a7c1
train
class
class TFCompressionTestCase(test.TestCase): def setUp(self): super(TFCompressionTestCase, self).setUp() self._num_files = 2 self._num_records = 7 def _Record(self, f, r): return compat.as_bytes("Record %d of file %d" % (r, f)) def _CreateFiles(self, options=None, prefix=""): file...
class TFCompressionTestCase(test.TestCase):
def setUp(self): super(TFCompressionTestCase, self).setUp() self._num_files = 2 self._num_records = 7 def _Record(self, f, r): return compat.as_bytes("Record %d of file %d" % (r, f)) def _CreateFiles(self, options=None, prefix=""): filenames = [] for i in range(self._num_files)...
, A gallant knight, In sunshine and in shadow, Had journeyed long, Singing a song, In search of Eldorado. But he grew old This knight so bold And o'er his heart a shadow Fell as he found No spot of ground That looked like Eldorado. And, as his strength ...
167
168
560
9
158
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
TFCompressionTestCase
TFCompressionTestCase
79
139
79
80
d450d4eead133bfa72c83dea4ea1d2142c022382
bigcode/the-stack
train
3fdc3a196ce1e1d18ecb305d
train
class
class TextLineReaderTest(test.TestCase): def setUp(self): super(TextLineReaderTest, self).setUp() self._num_files = 2 self._num_lines = 5 def _LineText(self, f, l): return compat.as_bytes("%d: %d" % (f, l)) def _CreateFiles(self, crlf=False): filenames = [] for i in range(se...
class TextLineReaderTest(test.TestCase):
def setUp(self): super(TextLineReaderTest, self).setUp() self._num_files = 2 self._num_lines = 5 def _LineText(self, f, l): return compat.as_bytes("%d: %d" % (f, l)) def _CreateFiles(self, crlf=False): filenames = [] for i in range(self._num_files): fn = os.path.join(sel...
requested 1, current size 0\\)"): self.evaluate([key, value]) @test_util.run_deprecated_v1 def testInfiniteEpochs(self): reader = io_ops.WholeFileReader("test_reader") queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) enqueue = queue.enqueue_many([self._filenames]) key, ...
202
202
676
9
193
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
TextLineReaderTest
TextLineReaderTest
345
411
345
346
b4d8b2746f4e6f5ac730b482f45d7bd128742373
bigcode/the-stack
train
8266628473074286002b8969
train
class
class LMDBReaderTest(test.TestCase): def setUp(self): super(LMDBReaderTest, self).setUp() # Copy database out because we need the path to be writable to use locks. path = os.path.join(prefix_path, "lmdb", "testdata", "data.mdb") self.db_path = os.path.join(self.get_temp_dir(), "data.mdb") ...
class LMDBReaderTest(test.TestCase):
def setUp(self): super(LMDBReaderTest, self).setUp() # Copy database out because we need the path to be writable to use locks. path = os.path.join(prefix_path, "lmdb", "testdata", "data.mdb") self.db_path = os.path.join(self.get_temp_dir(), "data.mdb") shutil.copy(path, self.db_path) @te...
in range(3): queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) reader = io_ops.TextLineReader() _, line = reader.read(queue) output = [] t = threading.Thread( target=AsyncReaderTest._RunSessionAndSave, args=(sess, [line], output)) ...
255
256
883
9
246
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
LMDBReaderTest
LMDBReaderTest
752
836
752
753
238f16797d3913cf115caa33d72bc4310948f88f
bigcode/the-stack
train
ced92dd2a4c61f734d300ad1
train
class
class FixedLengthRecordReaderTest(TFCompressionTestCase): def setUp(self): super(FixedLengthRecordReaderTest, self).setUp() self._num_files = 2 self._header_bytes = 5 self._record_bytes = 3 self._footer_bytes = 2 self._hop_bytes = 2 def _Record(self, f, r): return compat.a...
class FixedLengthRecordReaderTest(TFCompressionTestCase):
def setUp(self): super(FixedLengthRecordReaderTest, self).setUp() self._num_files = 2 self._header_bytes = 5 self._record_bytes = 3 self._footer_bytes = 2 self._hop_bytes = 2 def _Record(self, f, r): return compat.as_bytes(str(f * 2 + r) * self._record_bytes) def _Overla...
=False)) @test_util.run_deprecated_v1 def testOneEpochCRLF(self): self._testOneEpoch(self._CreateFiles(crlf=True)) @test_util.run_deprecated_v1 def testSkipHeaderLines(self): files = self._CreateFiles() reader = io_ops.TextLineReader(skip_header_lines=1, name="test_reader") queue = d...
255
256
1,999
12
243
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
FixedLengthRecordReaderTest
FixedLengthRecordReaderTest
414
620
414
415
258eb3aedaaeafb107dc42c5628593152c3dd8e8
bigcode/the-stack
train
748d02946317a520ef95a7c5
train
class
class IdentityReaderTest(test.TestCase): def _ExpectRead(self, key, value, expected): k, v = self.evaluate([key, value]) self.assertAllEqual(expected, k) self.assertAllEqual(expected, v) @test_util.run_deprecated_v1 def testOneEpoch(self): reader = io_ops.IdentityReader("test_reader") ...
class IdentityReaderTest(test.TestCase):
def _ExpectRead(self, key, value, expected): k, v = self.evaluate([key, value]) self.assertAllEqual(expected, k) self.assertAllEqual(expected, v) @test_util.run_deprecated_v1 def testOneEpoch(self): reader = io_ops.IdentityReader("test_reader") work_completed = reader.num_work_units_c...
(cdata) return zfn def _GzipCompressFile(self, infile, name="tfrecord.gz"): # gzip compress the file and write compressed contents to file. with open(infile, "rb") as f: cdata = f.read() gzfn = os.path.join(self.get_temp_dir(), name) with gzip.GzipFile(gzfn, "wb") as f: f.w...
256
256
1,331
8
247
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
IdentityReaderTest
IdentityReaderTest
142
284
142
143
2b16e614adf469eec327ef20e25a4471f524c447
bigcode/the-stack
train
84c98d8f32c60a9d86d25605
train
class
class AsyncReaderTest(test.TestCase): @test_util.run_deprecated_v1 def testNoDeadlockFromQueue(self): """Tests that reading does not block main execution threads.""" config = config_pb2.ConfigProto( inter_op_parallelism_threads=1, intra_op_parallelism_threads=1) with self.session(config=...
class AsyncReaderTest(test.TestCase): @test_util.run_deprecated_v1
def testNoDeadlockFromQueue(self): """Tests that reading does not block main execution threads.""" config = config_pb2.ConfigProto( inter_op_parallelism_threads=1, intra_op_parallelism_threads=1) with self.session(config=config) as sess: thread_data_t = collections.namedtuple("thread_da...
], shapes=()) key, value = reader.read(queue) self.evaluate(queue.enqueue_many([files])) self.evaluate(queue.close()) for i in range(self._num_files): for j in range(self._num_records): k, v = self.evaluate([key, value]) self.assertTrue(compat.as_text(k).startswith("%s:" %...
110
110
368
18
92
uve/tensorflow
tensorflow/python/kernel_tests/reader_ops_test.py
Python
AsyncReaderTest
AsyncReaderTest
710
749
710
712
45127ea5435a80a3ef477ebd0d9137d85baf6679
bigcode/the-stack
train
77a91b682234c32acc44679d
train
class
class LoginForm(AuthenticationForm): username = forms.CharField( required=True, widget=forms.EmailInput(attrs={'placeholder': 'E-mail'}) ) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) class Meta: m...
class LoginForm(AuthenticationForm):
username = forms.CharField( required=True, widget=forms.EmailInput(attrs={'placeholder': 'E-mail'}) ) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) class Meta: model = User fields = ('userna...
from django import forms from django.contrib.auth import authenticate, get_user_model from django.contrib.auth.forms import AuthenticationForm from authtools import forms as authforms User = get_user_model() class LoginForm(AuthenticationForm):
47
64
75
6
41
crhowell/stbuilder-docker
web/accounts/forms.py
Python
LoginForm
LoginForm
11
23
11
11
bd57bfe17b932bd9c7ee94c069bc359f082b5187
bigcode/the-stack
train
cac5231e892b6d83ef1bfe35
train
class
class SignUpForm(authforms.UserCreationForm): email = forms.CharField( required=True, widget=forms.EmailInput(attrs={'placeholder': 'E-mail'}) ) password1 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) password2 = fo...
class SignUpForm(authforms.UserCreationForm):
email = forms.CharField( required=True, widget=forms.EmailInput(attrs={'placeholder': 'E-mail'}) ) password1 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) password2 = forms.CharField( required=True, w...
Input(attrs={'placeholder': 'E-mail'}) ) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) class Meta: model = User fields = ('username', 'password') class SignUpForm(authforms.UserCreationForm):
64
64
105
10
54
crhowell/stbuilder-docker
web/accounts/forms.py
Python
SignUpForm
SignUpForm
26
43
26
27
f2ae177c11f58185266bf9d4413587d5c70c8745
bigcode/the-stack
train
b9d9b3a0e0f1b15f282a3418
train
class
class AttentionWrapper(object): def __init__(self, hidden_size, input_size, hs, scope_name): self.hs = tf.transpose(hs, [1,0,2]) self.hidden_size = hidden_size self.input_size = input_size self.scope_name = scope_name self.params = {} with tf.variable_scope(scope_nam...
class AttentionWrapper(object):
def __init__(self, hidden_size, input_size, hs, scope_name): self.hs = tf.transpose(hs, [1,0,2]) self.hidden_size = hidden_size self.input_size = input_size self.scope_name = scope_name self.params = {} with tf.variable_scope(scope_name): self.Wh = tf.get...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-4-27 下午8:35 # @Author : Tianyu Liu import tensorflow as tf import pickle class AttentionWrapper(object):
52
170
569
5
46
JohnKurian/TableGPT
AttentionUnit.py
Python
AttentionWrapper
AttentionWrapper
10
56
10
10
75c9b2016215a9ee2e1df50d1c71b1a8653117e7
bigcode/the-stack
train
d33c6bc850b12b20ebc97fb0
train
function
def read_cap(cap, scale_factor=1.0, output_stride=16): res, img = cap.read() if not res: raise IOError("webcam failure") return _process_input(img, scale_factor, output_stride)
def read_cap(cap, scale_factor=1.0, output_stride=16):
res, img = cap.read() if not res: raise IOError("webcam failure") return _process_input(img, scale_factor, output_stride)
_img * (2.0 / 255.0) - 1.0 input_img = input_img.reshape(1, target_height, target_width, 3) return input_img, source_img, scale def read_cap(cap, scale_factor=1.0, output_stride=16):
64
64
51
17
46
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
read_cap
read_cap
25
29
25
25
03218114c592021d3ae347c92a7c8b72f8c33254
bigcode/the-stack
train
80704767da18418bcf381af9
train
function
def _process_input(source_img, scale_factor=1.0, output_stride=16): target_width, target_height = valid_resolution( source_img.shape[1] * scale_factor, source_img.shape[0] * scale_factor, output_stride=output_stride) scale = np.array([source_img.shape[0] / target_height, source_img.shape[1] / target_wid...
def _process_input(source_img, scale_factor=1.0, output_stride=16):
target_width, target_height = valid_resolution( source_img.shape[1] * scale_factor, source_img.shape[0] * scale_factor, output_stride=output_stride) scale = np.array([source_img.shape[0] / target_height, source_img.shape[1] / target_width]) input_img = cv2.resize(source_img, (target_width, target_h...
target_width = (int(width) // output_stride) * output_stride + 1 target_height = (int(height) // output_stride) * output_stride + 1 return target_width, target_height def _process_input(source_img, scale_factor=1.0, output_stride=16):
64
64
180
19
44
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
_process_input
_process_input
13
22
13
13
33d46052de8e82d89883af66a5403264eb7f953d
bigcode/the-stack
train
0afad81fedf70fab0103a05f
train
function
def read_imgfile(path, scale_factor=1.0, output_stride=16): img = cv2.imread(path) return _process_input(img, scale_factor, output_stride)
def read_imgfile(path, scale_factor=1.0, output_stride=16):
img = cv2.imread(path) return _process_input(img, scale_factor, output_stride)
scale_factor=1.0, output_stride=16): res, img = cap.read() if not res: raise IOError("webcam failure") return _process_input(img, scale_factor, output_stride) def read_imgfile(path, scale_factor=1.0, output_stride=16):
64
64
39
18
46
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
read_imgfile
read_imgfile
32
34
32
32
ed59e12fc813fa53266f6dc216b1b45532d1a9db
bigcode/the-stack
train
2e066adfac6f49bb7f1b1daf
train
function
def get_adjacent_keypoints(keypoint_scores, keypoint_coords, min_confidence=0.1): results = [] for left, right in posenet.CONNECTED_PART_INDICES: if keypoint_scores[left] < min_confidence or keypoint_scores[right] < min_confidence: continue results.append( np.array([keypo...
def get_adjacent_keypoints(keypoint_scores, keypoint_coords, min_confidence=0.1):
results = [] for left, right in posenet.CONNECTED_PART_INDICES: if keypoint_scores[left] < min_confidence or keypoint_scores[right] < min_confidence: continue results.append( np.array([keypoint_coords[left][::-1], keypoint_coords[right][::-1]]).astype(np.int32), )...
Point(kc[1], kc[0], 10. * ks)) out_img = cv2.drawKeypoints(img, cv_keypoints, outImage=np.array([])) return out_img def get_adjacent_keypoints(keypoint_scores, keypoint_coords, min_confidence=0.1):
64
64
101
22
41
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
get_adjacent_keypoints
get_adjacent_keypoints
52
60
52
52
e98ad1a1b74330da6072d40f2c109c3c4d21a764
bigcode/the-stack
train
ac5a4d49af471df5c0a1179a
train
function
def valid_resolution(width, height, output_stride=16): target_width = (int(width) // output_stride) * output_stride + 1 target_height = (int(height) // output_stride) * output_stride + 1 return target_width, target_height
def valid_resolution(width, height, output_stride=16):
target_width = (int(width) // output_stride) * output_stride + 1 target_height = (int(height) // output_stride) * output_stride + 1 return target_width, target_height
import cv2 import numpy as np import posenet.constants def valid_resolution(width, height, output_stride=16):
26
64
58
12
13
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
valid_resolution
valid_resolution
7
10
7
7
52f59ab7390ccc18ae4ae4836ddd6ce6ad9365a6
bigcode/the-stack
train
de3eeefec02c88614c0aa4d2
train
function
def draw_keypoints( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5): cv_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_confidence: continue for ks, kc in zip(keypoint_scores[ii,...
def draw_keypoints( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5):
cv_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_confidence: continue for ks, kc in zip(keypoint_scores[ii, :], keypoint_coords[ii, :, :]): if ks < min_part_confidence: continue cv_keypoints.append(cv2.KeyPoint...
output_stride=16): img = cv2.imread(path) return _process_input(img, scale_factor, output_stride) def draw_keypoints( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5):
64
64
150
38
26
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
draw_keypoints
draw_keypoints
37
49
37
39
936a30b1fabc49e80a802395eb2aa150a706ac4a
bigcode/the-stack
train
1e24a66f242fca9537bbaa6f
train
function
def draw_skel_and_kp( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_score=0.5, min_part_score=0.5): out_img = img adjacent_keypoints = [] cv_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_score: continue new...
def draw_skel_and_kp( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_score=0.5, min_part_score=0.5):
out_img = img adjacent_keypoints = [] cv_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_score: continue new_keypoints = get_adjacent_keypoints( keypoint_scores[ii, :], keypoint_coords[ii, :, :], min_part_score) adjacent_ke...
.extend(new_keypoints) out_img = cv2.polylines(out_img, adjacent_keypoints, isClosed=False, color=(255, 255, 0)) return out_img def draw_skel_and_kp( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_score=0.5, min_part_score=0.5):
79
79
264
39
39
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
draw_skel_and_kp
draw_skel_and_kp
78
101
78
80
bb10341513feac0942c7e8d3aab6c1b05c594624
bigcode/the-stack
train
347a24eb3b1feb60e449b199
train
function
def draw_skeleton( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5): out_img = img adjacent_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_confidence: continue new_keypoints ...
def draw_skeleton( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5):
out_img = img adjacent_keypoints = [] for ii, score in enumerate(instance_scores): if score < min_pose_confidence: continue new_keypoints = get_adjacent_keypoints( keypoint_scores[ii, :], keypoint_coords[ii, :, :], min_part_confidence) adjacent_keypoints.exten...
_coords[left][::-1], keypoint_coords[right][::-1]]).astype(np.int32), ) return results def draw_skeleton( img, instance_scores, keypoint_scores, keypoint_coords, min_pose_confidence=0.5, min_part_confidence=0.5):
64
64
148
38
25
MatusMaruna/posenet-squats-evaluator
posenet/utils.py
Python
draw_skeleton
draw_skeleton
63
75
63
65
7b6dcaf75b3f76f143c198686e89ced401ef8d46
bigcode/the-stack
train
3cd7c158441db9d7abc92799
train
class
class DeterminantOpTest(test.TestCase): def _compareDeterminantBase(self, matrix_x, tf_ans): out = tf_ans.eval() shape = matrix_x.shape if shape[-1] == 0 and shape[-2] == 0: np_ans = np.ones(shape[:-2]).astype(matrix_x.dtype) else: np_ans = np.array(np.linalg.det(matrix_x)).astype(matrix_...
class DeterminantOpTest(test.TestCase):
def _compareDeterminantBase(self, matrix_x, tf_ans): out = tf_ans.eval() shape = matrix_x.shape if shape[-1] == 0 and shape[-2] == 0: np_ans = np.ones(shape[:-2]).astype(matrix_x.dtype) else: np_ans = np.array(np.linalg.det(matrix_x)).astype(matrix_x.dtype) self.assertShapeEqual(np_ans...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
248
256
1,556
10
237
TTrapper/tensorflow
tensorflow/python/kernel_tests/determinant_op_test.py
Python
DeterminantOpTest
DeterminantOpTest
33
139
33
34
d6964b542700e5fe7818ac6ff1bc693be2f959f0
bigcode/the-stack
train
d1efa1919913c04e40bc0e97
train
class
class MatrixDeterminantBenchmark(test.Benchmark): shapes = [ (4, 4), (10, 10), (16, 16), (101, 101), (256, 256), (1000, 1000), (1024, 1024), (2048, 2048), (513, 4, 4), (513, 16, 16), (513, 256, 256), ] def _GenerateMatrix(self, shape): batch_...
class MatrixDeterminantBenchmark(test.Benchmark):
shapes = [ (4, 4), (10, 10), (16, 16), (101, 101), (256, 256), (1000, 1000), (1024, 1024), (2048, 2048), (513, 4, 4), (513, 16, 16), (513, 256, 256), ] def _GenerateMatrix(self, shape): batch_shape = shape[:-2] shape = shape[-2:] asser...
testConcurrentExecutesWithoutError(self): with self.test_session(use_gpu=True) as sess: matrix1 = random_ops.random_normal([5, 5], seed=42) matrix2 = random_ops.random_normal([5, 5], seed=42) det1 = linalg_ops.matrix_determinant(matrix1) det2 = linalg_ops.matrix_determinant(matrix2) d...
124
124
414
10
114
TTrapper/tensorflow
tensorflow/python/kernel_tests/determinant_op_test.py
Python
MatrixDeterminantBenchmark
MatrixDeterminantBenchmark
142
192
142
143
3d541db9eefed8d739df49bed0818d5e09d2f583
bigcode/the-stack
train
9501378bfc3ac9d41a8393b5
train
function
def blist(data): if type(data) is int: data=[data] elif type(data) is bytes: data = bytearray(data) elif type(data) is str: data = bytearray(data.encode("utf8")) if type(data) is not list: data=list(data) return data
def blist(data):
if type(data) is int: data=[data] elif type(data) is bytes: data = bytearray(data) elif type(data) is str: data = bytearray(data.encode("utf8")) if type(data) is not list: data=list(data) return data
C_TIMEOUT = 0x0702 # set timeout in units of 10 ms # cast given object to a list of ints, works with python 2 or 3, supports int, # bytes, str, bytearray, memoryview, tuple (and list of course) def blist(data):
64
64
66
5
59
glitchub/plio
i2c.py
Python
blist
blist
34
39
34
34
7ca7158833b75ecf20f465c077dc07a2261eba72
bigcode/the-stack
train
352ce65a328cab22abc3e66a
train
class
class i2c: # init i2c controller, note bus == None enables stub operation def __init__(self, bus, addr, retries=None, timeout=None): assert 0x07 < addr < 0x78 # disallow address ranges 0000xxx and 1111xxx if bus is not None: self.fd=os.open("/dev/i2c-%d" % bus, os.O_RDWR) else: self.fd ...
class i2c: # init i2c controller, note bus == None enables stub operation
def __init__(self, bus, addr, retries=None, timeout=None): assert 0x07 < addr < 0x78 # disallow address ranges 0000xxx and 1111xxx if bus is not None: self.fd=os.open("/dev/i2c-%d" % bus, os.O_RDWR) else: self.fd = None self.addr=addr if retries is not None: self.set_retries(...
= 42 # max value of nmsgs # Various IOCTLs I2C_RDWR = 0x0707 # perform combined R/W transfer (one STOP only) I2C_RETRIES = 0x0701 # number of times a device address should be polled when not acknowledging I2C_TIMEOUT = 0x0702 # set timeout in units of 10 ms # cast given object ...
215
215
718
21
193
glitchub/plio
i2c.py
Python
i2c
i2c
41
101
41
43
500821d2ef5e24c5087ea49bbb0af478dec7f61d
bigcode/the-stack
train
946dd524d3fc40cf6ef4c2f8
train
class
class i2c_rdwr_ioctl_data(Structure): _fields_ = [ ("msgs", c_void_p), # address of array of i2c_msgs ("nmsgs", c_uint) # number of i2c_msgs in the array ]
class i2c_rdwr_ioctl_data(Structure):
_fields_ = [ ("msgs", c_void_p), # address of array of i2c_msgs ("nmsgs", c_uint) # number of i2c_msgs in the array ]
C_M_RD ("len", c_ushort), # length of buffer ("buf", c_void_p) # pointer to buffer ] I2C_M_RD = 1 # if set, read from slave class i2c_rdwr_ioctl_data(Structure):
64
64
59
11
52
glitchub/plio
i2c.py
Python
i2c_rdwr_ioctl_data
i2c_rdwr_ioctl_data
19
23
19
19
17bb4bce8e267e74b9f4089725395f0bca5759d5
bigcode/the-stack
train
967b7a598d787b2761c3b47b
train
class
class i2c_msg(Structure): _fields_ = [ ("addr", c_ushort), # slave address ("flags", c_ushort), # 0 or I2C_M_RD ("len", c_ushort), # length of buffer ("buf", c_void_p) # pointer to buffer ]
class i2c_msg(Structure):
_fields_ = [ ("addr", c_ushort), # slave address ("flags", c_ushort), # 0 or I2C_M_RD ("len", c_ushort), # length of buffer ("buf", c_void_p) # pointer to buffer ]
""" Provide access to /dev/i2c-* devices """ from __future__ import print_function import os, fcntl from ctypes import * from itertools import count # This information from linux/i2c-dev.h and linux/i2c.h class i2c_msg(Structure):
61
64
79
8
52
glitchub/plio
i2c.py
Python
i2c_msg
i2c_msg
10
16
10
10
b86ac336275b8d834f3fd819bab5e73a2c7ba1c0
bigcode/the-stack
train
6b68e93958ddb2372ad36218
train
function
def thresh_callback(val): threshold = val canny_output = cv.Canny(src_gray, threshold, threshold * 2) contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) contours_poly = [None]*len(contours) boundRect = [None]*len(contours) centers = [None]*len(contours) radius...
def thresh_callback(val):
threshold = val canny_output = cv.Canny(src_gray, threshold, threshold * 2) contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) contours_poly = [None]*len(contours) boundRect = [None]*len(contours) centers = [None]*len(contours) radius = [None]*len(contours) ...
from __future__ import print_function import cv2 as cv import numpy as np import argparse import random as rng rng.seed(12345) def thresh_callback(val):
38
98
328
5
33
Vincent-Maladiere/opencv-advanced-tutorial
src/preprocessing/bounding_box.py
Python
thresh_callback
thresh_callback
9
33
9
10
9bdad02ae153a526572e714b3e5d27008fce2910
bigcode/the-stack
train
d766009830a8488a45cab275
train
function
@click.command() @click.option('--server', default="nginx", help='Name of the web server') @click.option('--log', help="Web server's log directory.") def audit(server, log): if server == 'nginx': generate_csv_reports(log) return 0
@click.command() @click.option('--server', default="nginx", help='Name of the web server') @click.option('--log', help="Web server's log directory.") def audit(server, log):
if server == 'nginx': generate_csv_reports(log) return 0
py_logan.""" import sys import click from py_logan.nginx.audit import generate_csv_reports @click.command() @click.option('--server', default="nginx", help='Name of the web server') @click.option('--log', help="Web server's log directory.") def audit(server, log):
64
64
62
42
21
wasi0013/python-loganalytics
py_logan/cli.py
Python
audit
audit
6
13
6
9
4f7965e6186b33b3fec1eae5f1afeff594dab99b
bigcode/the-stack
train
029a75b81c1a85b5681322e8
train
function
def create_missing_ipc_error_message(ipc_path: Path) -> str: log_message = ( f"The IPC path at {str(ipc_path)} is not found. \n" "Please run " "'trinity --data-dir <path-to-running-nodes-data-dir> attach' " "or 'trinity attach <path-to-jsonrpc.ipc>'" "to specify the IPC path....
def create_missing_ipc_error_message(ipc_path: Path) -> str:
log_message = ( f"The IPC path at {str(ipc_path)} is not found. \n" "Please run " "'trinity --data-dir <path-to-running-nodes-data-dir> attach' " "or 'trinity attach <path-to-jsonrpc.ipc>'" "to specify the IPC path." ) return log_message
from pathlib import Path def create_missing_ipc_error_message(ipc_path: Path) -> str:
21
64
95
16
4
dendisuhubdy/trinity
trinity/_utils/log_messages.py
Python
create_missing_ipc_error_message
create_missing_ipc_error_message
4
12
4
4
2cdcea4e4d58cffc251b9972b4788f32ca708cf4
bigcode/the-stack
train
f52379b7cfcb042011e36c45
train
function
@logger.catch def main(): s = time.perf_counter() task_q = Queue() done_q = Queue() task_q.put(basepath) processes = [ Process(target=worker, args=(task_q, done_q)) for _ in range(NUMBER_OF_PROCESSES) ] for process in processes: process.start() while not task_...
@logger.catch def main():
s = time.perf_counter() task_q = Queue() done_q = Queue() task_q.put(basepath) processes = [ Process(target=worker, args=(task_q, done_q)) for _ in range(NUMBER_OF_PROCESSES) ] for process in processes: process.start() while not task_q.empty() or task_q.qsize(...
DBG('no item') continue if item == 'STOP': logger.info('Stopping...') input_q.task_done() return DBG(item) path = Path(item) dirs = map(str, filter(Path.is_dir, path.iterdir())) [*map(input_q.put, dirs)] output_q.put(item) ...
154
154
514
7
146
brl0/bripy
scraps/listdirs.py
Python
main
main
51
123
51
52
0ebfa10018ab9c266049e17897a1614210912fc8
bigcode/the-stack
train
f774b94420c650cd7ab7c118
train
function
def worker(input_q, output_q): while True or not input_q.empty() or input_q.qsize(): item = input_q.get() if not item: sleep(0.05) DBG('no item') continue if item == 'STOP': logger.info('Stopping...') input_q.task_done() ...
def worker(input_q, output_q):
while True or not input_q.empty() or input_q.qsize(): item = input_q.get() if not item: sleep(0.05) DBG('no item') continue if item == 'STOP': logger.info('Stopping...') input_q.task_done() return DBG(item) ...
from time import sleep import sys from bripy.bllb.logging import get_dbg, setup_logging logger = setup_logging(True, "INFO", loguru_enqueue=True) DBG = get_dbg(logger) basepath = '.' NUMBER_OF_PROCESSES = 1 def worker(input_q, output_q):
64
64
120
8
55
brl0/bripy
scraps/listdirs.py
Python
worker
worker
17
33
17
17
b9356526fa4613e96c8030e0b0b102d3f9ab03b0
bigcode/the-stack
train
27468bc1af02273c85a6cd9d
train
function
def get_q(q): results = [] while not q.empty() or q.qsize(): item = q.get() if item == 'STOP': DBG('STOP get_q') q.task_done() break DBG(item) if item: results.append(item) q.task_done() return results
def get_q(q):
results = [] while not q.empty() or q.qsize(): item = q.get() if item == 'STOP': DBG('STOP get_q') q.task_done() break DBG(item) if item: results.append(item) q.task_done() return results
('Stopping...') input_q.task_done() return DBG(item) path = Path(item) dirs = map(str, filter(Path.is_dir, path.iterdir())) [*map(input_q.put, dirs)] output_q.put(item) input_q.task_done() def get_q(q):
64
64
70
5
59
brl0/bripy
scraps/listdirs.py
Python
get_q
get_q
36
48
36
36
543e36cc9da8f97d3998ba8570e4e26f85b49b73
bigcode/the-stack
train
ff9d30672d93d66eb362f2f6
train
function
def _get_struct_I(): global _struct_I return _struct_I
def _get_struct_I():
global _struct_I return _struct_I
val1.value,) = _get_struct_d().unpack(str[start:end]) self.positions.append(val1) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I():
64
64
18
6
57
ankit131199/Rebellious-Cowards
devel/lib/python2.7/dist-packages/brics_actuator/msg/_JointPositions.py
Python
_get_struct_I
_get_struct_I
290
292
290
290
72b073a01b474fd54b1e1016eaaaa07c0526f426
bigcode/the-stack
train
9b0aba58738952139cc5954d
train
function
def _get_struct_f(): global _struct_f if _struct_f is None: _struct_f = struct.Struct("<f") return _struct_f
def _get_struct_f():
global _struct_f if _struct_f is None: _struct_f = struct.Struct("<f") return _struct_f
_2I = None def _get_struct_2I(): global _struct_2I if _struct_2I is None: _struct_2I = struct.Struct("<2I") return _struct_2I _struct_f = None def _get_struct_f():
64
64
36
6
57
ankit131199/Rebellious-Cowards
devel/lib/python2.7/dist-packages/brics_actuator/msg/_JointPositions.py
Python
_get_struct_f
_get_struct_f
306
310
306
306
8df239297b1f542dee4e36b02a2f54ef26ff3bd2
bigcode/the-stack
train
c2c19408ae39d718dda06b77
train
function
def _get_struct_d(): global _struct_d if _struct_d is None: _struct_d = struct.Struct("<d") return _struct_d
def _get_struct_d():
global _struct_d if _struct_d is None: _struct_d = struct.Struct("<d") return _struct_d
return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_d = None def _get_struct_d():
64
64
36
6
57
ankit131199/Rebellious-Cowards
devel/lib/python2.7/dist-packages/brics_actuator/msg/_JointPositions.py
Python
_get_struct_d
_get_struct_d
294
298
294
294
535a8148055c077c2a666cd813654af59f7e5b19
bigcode/the-stack
train
ef447a412af373064e7b2501
train
function
def _get_struct_2I(): global _struct_2I if _struct_2I is None: _struct_2I = struct.Struct("<2I") return _struct_2I
def _get_struct_2I():
global _struct_2I if _struct_2I is None: _struct_2I = struct.Struct("<2I") return _struct_2I
_I return _struct_I _struct_d = None def _get_struct_d(): global _struct_d if _struct_d is None: _struct_d = struct.Struct("<d") return _struct_d _struct_2I = None def _get_struct_2I():
64
64
47
8
55
ankit131199/Rebellious-Cowards
devel/lib/python2.7/dist-packages/brics_actuator/msg/_JointPositions.py
Python
_get_struct_2I
_get_struct_2I
300
304
300
300
96fad3bf2b655934bd086b999f03620a34516698
bigcode/the-stack
train
cf444885957b2ba68600c724
train
class
class JointPositions(genpy.Message): _md5sum = "2b7638f5c85f5257bef140a00cd0eec3" _type = "brics_actuator/JointPositions" _has_header = False #flag to mark the presence of a Header object _full_text = """Poison poisonStamp JointValue[] positions =================================================================...
class JointPositions(genpy.Message):
_md5sum = "2b7638f5c85f5257bef140a00cd0eec3" _type = "brics_actuator/JointPositions" _has_header = False #flag to mark the presence of a Header object _full_text = """Poison poisonStamp JointValue[] positions ================================================================================ MSG: brics_actuator/P...
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from brics_actuator/JointPositions.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import brics_actuator.msg import genpy class JointPositions(genpy.Message):
79
256
2,557
7
71
ankit131199/Rebellious-Cowards
devel/lib/python2.7/dist-packages/brics_actuator/msg/_JointPositions.py
Python
JointPositions
JointPositions
11
287
11
11
82dbb0c18de01b96d8ce26eee1cfbf709e3b2983
bigcode/the-stack
train
f11598fe46339432cb45254d
train
class
class Migration(migrations.Migration): dependencies = [ ('postjob', '0002_jobform_favorites'), ] operations = [ migrations.RemoveField( model_name='jobform', name='favorites', ), ]
class Migration(migrations.Migration):
dependencies = [ ('postjob', '0002_jobform_favorites'), ] operations = [ migrations.RemoveField( model_name='jobform', name='favorites', ), ]
# Generated by Django 3.0.7 on 2020-11-13 06:46 from django.db import migrations class Migration(migrations.Migration):
36
64
51
7
28
Rypin/AviationJobBoardPortal
aviation-project/postjob/migrations/0003_remove_jobform_favorites.py
Python
Migration
Migration
6
17
6
7
b34344178c8758c79e07deea014dd7062d111837
bigcode/the-stack
train
968e288973ab8b39008c5267
train
function
def sysloggable_excinfo(*excinfo): """Returns exception information as a string for syslog. The returned string will have no newlines, the exception type and message first in case the line is truncated, and anything else deemed to make it nicer for delivery to syslog. :param excinfo: The exception...
def sysloggable_excinfo(*excinfo):
"""Returns exception information as a string for syslog. The returned string will have no newlines, the exception type and message first in case the line is truncated, and anything else deemed to make it nicer for delivery to syslog. :param excinfo: The exception info (exctype, value, traceback) s...
def format(self, record): msg = logging.Formatter.format(self, record).strip() if record.txn and record.txn not in msg: msg = '%s txn:%s' % (msg, record.txn) return msg def sysloggable_excinfo(*excinfo):
64
64
154
10
53
gholt/python-brim
brim/log.py
Python
sysloggable_excinfo
sysloggable_excinfo
102
117
102
102
fb3fbacfb08a79b10eecff3c00035e03b9810274
bigcode/the-stack
train
2cf330fd3ce1c9f8e9481c80
train
class
class _LogAdapter(logging.LoggerAdapter, object): """Extended LoggerAdapter for txn and server values and notice. Provides support for the thread/coroutine-local ``txn`` attribute, passing of the server name and txn attribute with each log record, and providing an additional :py:func:`notice()` method ...
class _LogAdapter(logging.LoggerAdapter, object):
"""Extended LoggerAdapter for txn and server values and notice. Provides support for the thread/coroutine-local ``txn`` attribute, passing of the server name and txn attribute with each log record, and providing an additional :py:func:`notice()` method for the new :py:attr:`NOTICE` log level. "...
Lock() NOTICE = 25 """An additional log level patched into the standard logging levels. This level is to be used for logging HTTP requests only so that it can be easily filtered on to form access logs. """ logging.NOTICE = NOTICE logging._levelNames[NOTICE] = 'NOTICE' SysLogHandler.priority_map['NOTICE'] = 'notice' cl...
84
84
282
10
74
gholt/python-brim
brim/log.py
Python
_LogAdapter
_LogAdapter
47
82
47
47
c2236ef586e7f9598b33a9babebe83bc79a380b4
bigcode/the-stack
train
8d2f74e9632d4680220579bd
train
function
def get_logger(route, name, level, facility='LOG_USER', console=False): """Returns a Logger based on the information given. :param route: The str log route, which is often the same as the name but does not have to be. Think of this as the key for the logger in source code. :param name: The ...
def get_logger(route, name, level, facility='LOG_USER', console=False):
"""Returns a Logger based on the information given. :param route: The str log route, which is often the same as the name but does not have to be. Think of this as the key for the logger in source code. :param name: The str log name, this is the name sent to the underlying log system...
delivery to syslog. :param excinfo: The exception info (exctype, value, traceback) such as returned with sys.exc_info. """ if not excinfo: excinfo = exc_info() if excinfo[0] == KeyboardInterrupt: return 'KeyboardInterrupt' lines = ''.join(format_exception(*excinfo)).strip()...
113
113
378
17
96
gholt/python-brim
brim/log.py
Python
get_logger
get_logger
120
155
120
120
f76b17ddbcbd79d02f5112328a5980dc5a63d8b0
bigcode/the-stack
train
b75407807c8e191eace90d98
train
class
class _LogFormatter(logging.Formatter): """Extended Formatter for txn and server values. Always emits the server name and ensures the txn (if set) is in the log line somewhere. """ def __init__(self): logging.Formatter.__init__(self, '%(server)s %(message)s') def format(self, record):...
class _LogFormatter(logging.Formatter):
"""Extended Formatter for txn and server values. Always emits the server name and ensures the txn (if set) is in the log line somewhere. """ def __init__(self): logging.Formatter.__init__(self, '%(server)s %(message)s') def format(self, record): msg = logging.Formatter.format(...
(self, msg, *args, **kwargs): self.error('%s %s' % (msg, sysloggable_excinfo())) def notice(self, msg, *args, **kwargs): self.log(NOTICE, msg, *args, **kwargs) class _LogFormatter(logging.Formatter):
64
64
121
8
56
gholt/python-brim
brim/log.py
Python
_LogFormatter
_LogFormatter
85
99
85
85
3ecfa0227c22f309545af6ad7c076d524aa63c32
bigcode/the-stack
train
2a254eac05ae189f15fbd213
train
class
class Logs: """ Logs join and leave messages, bans and unbans, and member changes. """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) welcome_msg = """ Hello {0}, welcome to the {1} server on Discord! Please review all of the rule...
class Logs:
""" Logs join and leave messages, bans and unbans, and member changes. """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) welcome_msg = """ Hello {0}, welcome to the {1} server on Discord! Please review all of the rules in {2} bef...
import discord import json from discord.ext import commands from sys import argv class Logs:
20
256
2,014
3
16
LolHacksRule/Kurisu
addons/logs.py
Python
Logs
Logs
6
174
6
6
c2570ef2fec5f6a1f500d972e2449349fb43fe46
bigcode/the-stack
train
613cd237b9abad97eec0cbf5
train
function
def setup(bot): bot.add_cog(Logs(bot))
def setup(bot):
bot.add_cog(Logs(bot))
.escape_name(member_after.nick)) if do_log: msg = "ℹ️ **Member update**: {} | {}#{}".format(member_after.mention, self.bot.escape_name(member_after.name), member_after.discriminator) + msg await self.bot.send_message(dest, msg) def setup(bot):
64
64
13
4
60
LolHacksRule/Kurisu
addons/logs.py
Python
setup
setup
176
177
176
176
aeb497daffa4fee65b8267a808bb1e3c5b4c4bde
bigcode/the-stack
train
f9a4653a261b6410976b8def
train
class
class RootACL: __acl__ = [ (Allow, 'admin', ALL_PERMISSIONS), (Allow, 'view', ['read']), ] def __init__(self, request): pass
class RootACL:
__acl__ = [ (Allow, 'admin', ALL_PERMISSIONS), (Allow, 'view', ['read']), ] def __init__(self, request): pass
from pyramid.config import Configurator from pyramid.authorization import ACLAuthorizationPolicy from pyramid.security import Allow, ALL_PERMISSIONS class RootACL:
29
64
45
4
24
IndigoShock/stocks_api
stocks_api/__init__.py
Python
RootACL
RootACL
6
13
6
6
10cf3d430ba802ab93d52f7176f772638f3e0ecd
bigcode/the-stack
train
ccb50ef42df5694cb819c8c5
train
function
def add_role_principles(userid, request): return request.jwt_claims.get('roles', [])
def add_role_principles(userid, request):
return request.jwt_claims.get('roles', [])
pyramid.security import Allow, ALL_PERMISSIONS class RootACL: __acl__ = [ (Allow, 'admin', ALL_PERMISSIONS), (Allow, 'view', ['read']), ] def __init__(self, request): pass def add_role_principles(userid, request):
64
64
21
10
53
IndigoShock/stocks_api
stocks_api/__init__.py
Python
add_role_principles
add_role_principles
16
17
16
16
e6ff0427c78c19b948f957e20e9f7a642ac9c2f4
bigcode/the-stack
train
a7172a5c67b4cfd53d5b414b
train
function
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_restful') config.include('pyramid_jwt') config.set_root_factory(RootACL) config.set_authorization_policy(ACLAuthorizationPolicy()) ...
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_restful') config.include('pyramid_jwt') config.set_root_factory(RootACL) config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_jwt_authentication_poli...
(Allow, 'admin', ALL_PERMISSIONS), (Allow, 'view', ['read']), ] def __init__(self, request): pass def add_role_principles(userid, request): return request.jwt_claims.get('roles', []) def main(global_config, **settings):
63
64
135
8
55
IndigoShock/stocks_api
stocks_api/__init__.py
Python
main
main
20
36
20
20
259379e94381866404bb25d14c0c799aa3db65dd
bigcode/the-stack
train
d6457e24a58830eccca85689
train
class
class RuleOrderGenerator(object): """ Generator to yield rules in the correct order for calculation. Parameters ---------- control_system : ControlSystem Fuzzy control system object, instance of `skfuzzy.ControlSystem`. Returns ------- out : Rule Fuzzy rules in computat...
class RuleOrderGenerator(object):
""" Generator to yield rules in the correct order for calculation. Parameters ---------- control_system : ControlSystem Fuzzy control system object, instance of `skfuzzy.ControlSystem`. Returns ------- out : Rule Fuzzy rules in computation order. """ def __init...
Find potentially new values new_values = [] for label, term in self.var.terms.items(): term._cut = term.membership_value[self.sim][idx] if term._cut is None: continue # No membership defined for this adjective # Faster to aggregate as list w/duplic...
256
256
909
6
249
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
RuleOrderGenerator
RuleOrderGenerator
672
791
672
672
52adfe56ccd017864193d39e9bf7f44e84694ed7
bigcode/the-stack
train
94ae693c1a18d2cb063c23ab
train
class
class ControlSystem(object): """ Base class to contain a Fuzzy Control System. Parameters ---------- rules : Rule or iterable of Rules, optional If provided, the system is initialized and populated with a set of fuzzy Rules (see ``skfuzzy.control.Rule``). This is optional. If ...
class ControlSystem(object):
""" Base class to contain a Fuzzy Control System. Parameters ---------- rules : Rule or iterable of Rules, optional If provided, the system is initialized and populated with a set of fuzzy Rules (see ``skfuzzy.control.Rule``). This is optional. If omitted the ControlSystem c...
""" controlsystem.py : Framework for the new fuzzy logic control system API. """ from __future__ import print_function, division import numpy as np import networkx as nx from warnings import warn from ..fuzzymath.fuzzy_ops import _interp_universe_fast from ..defuzzify import defuzz from ..fuzzymath import interp_memb...
159
188
629
5
153
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
ControlSystem
ControlSystem
25
115
25
25
09eaa2f921bb499ac0742d4aa62e7f040fd811e3
bigcode/the-stack
train
dc8670e0cc7facbb1ffd7233
train
class
class ControlSystemSimulation(object): """ Calculate results from a ControlSystem. Parameters ---------- control_system : ControlSystem A fuzzy ControlSystem object. clip_to_bounds : bool, optional Controls if input values should be clipped to the consequent universe ran...
class ControlSystemSimulation(object):
""" Calculate results from a ControlSystem. Parameters ---------- control_system : ControlSystem A fuzzy ControlSystem object. clip_to_bounds : bool, optional Controls if input values should be clipped to the consequent universe range. Default is True. cache : bool, ...
() out = "" for key, val in current_inputs.items(): out += "{0} : {1}\n".format(key, val) return out def _update_to_current(self): # Private method, used to store the current state of the system in a # cache, 'current', accessible before and after the unique_id c...
256
256
2,362
6
249
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
ControlSystemSimulation
ControlSystemSimulation
232
527
232
232
f58eee08171a4c3bdc70fe3f83f9dde5d8d1e22f
bigcode/the-stack
train
1b8fde4c9edb6eebb8351fe9
train
function
def _is_ndarray(object): """ Boolean response if object passed is a NumPy ndarray. """ return isinstance(object, np.ndarray)
def _is_ndarray(object):
""" Boolean response if object passed is a NumPy ndarray. """ return isinstance(object, np.ndarray)
graphs, which may not be disjoint self.graph = nx.compose(self.graph, rule.graph) def view(self): """ View a representation of the system NetworkX graph. """ fig, ax = ControlSystemVisualizer(self).view() fig.show() def _is_ndarray(object):
64
64
31
7
57
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
_is_ndarray
_is_ndarray
118
122
118
118
92548d79d6dc14a71d43a904bf2a1a2db6a12288
bigcode/the-stack
train
a4eb90fcf43257715f2e15dd
train
class
class CrispValueCalculator(object): """ Convert a calculated FuzzyVariable back into a crisp real number. Parameters ---------- fuzzy_var : FuzzyVariable The fuzzy variable to be defuzzified. sim : ControlSystemSimulation The simulation which holds all necessary data for this ca...
class CrispValueCalculator(object):
""" Convert a calculated FuzzyVariable back into a crisp real number. Parameters ---------- fuzzy_var : FuzzyVariable The fuzzy variable to be defuzzified. sim : ControlSystemSimulation The simulation which holds all necessary data for this calculation. """ def __init__...
}".format(r.antecedent, r.aggregate_firing[self])) print(" Activation (THEN-clause):") for c in r.consequent: assert isinstance(c, WeightedTerm) print(" {0:>54} : {1}".format(c, ...
255
256
1,140
6
249
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
CrispValueCalculator
CrispValueCalculator
530
669
530
530
4451e96d440c1c311c4f67753cd73f29a9748534
bigcode/the-stack
train
adb868b90a9ab1d89fe65e15
train
class
class _InputAcceptor(object): """ Set a single input value to an Antecedent in this ControlSystemSimulation. Inputs can be singletons or arrays, but all Antecedent inputs must match. If they are arrays, all must have the exact same shape. If they are arrays, the output(s) will carry the same shape...
class _InputAcceptor(object):
""" Set a single input value to an Antecedent in this ControlSystemSimulation. Inputs can be singletons or arrays, but all Antecedent inputs must match. If they are arrays, all must have the exact same shape. If they are arrays, the output(s) will carry the same shape as the inputs. """ d...
def fuzzy_variables(self): """ Generator which yields fuzzy variables in the system. This includes Antecedents, Consequents, and Intermediaries. """ for node in self.graph.nodes(): if isinstance(node, FuzzyVariable): yield node def addrule(self,...
256
256
856
7
249
SankaW/teamfx
backtesting/backtester/fuzzySystem/control/controlsystem.py
Python
_InputAcceptor
_InputAcceptor
125
229
125
125
a1395ae7c7dca0df686b646ca811d2f11244525e
bigcode/the-stack
train
f7bfd218c6fac427eb7eaef6
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('clubs', '0002_club_permissions'), ] operations = [ migrations.AlterModelOptions( name='clubmeeting', options={'ordering': ['moment'], 'verbos...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('clubs', '0002_club_permissions'), ] operations = [ migrations.AlterModelOptions( name='clubmeeting', options={'ordering': ['moment'], 'verbose_name': 'quedada'}, ), ...
# Generated by Django 2.1.7 on 2019-09-25 08:14 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration):
44
86
288
7
36
DarkoR12/dafi-system
clubs/migrations/0003_club_info.py
Python
Migration
Migration
7
47
7
8
7feca0aeeb1a268998522a4edcc342945ea7799e
bigcode/the-stack
train
298017c4951c520c73e2ff3f
train
class
class Dreamer(nn.Module): def __init__(self, state_dim, action_dim, device): super(Dreamer, self).__init__() self.state_dim = state_dim self.action_dim = action_dim self.device = device self.world_model = WorldModel(state_dim, action_dim, device) self.agent =...
class Dreamer(nn.Module):
def __init__(self, state_dim, action_dim, device): super(Dreamer, self).__init__() self.state_dim = state_dim self.action_dim = action_dim self.device = device self.world_model = WorldModel(state_dim, action_dim, device) self.agent = ActorCritic(FLOW_GRU_DIM ...
import numpy as np import torch import math import torch.nn as nn from WorldModel import WorldModel from ActorCritic import ActorCritic from params import EMBED_DIM, FLOW_GRU_DIM, WITH_CONTRASTIVE class Dreamer(nn.Module):
57
107
359
6
50
mahkons/Dreamer
dreamer-exp/Dreamer.py
Python
Dreamer
Dreamer
11
43
11
11
071a5278cd769c0402da935037b816d47f4086ba
bigcode/the-stack
train
bf4aa56081242c840d601cb1
train
function
def default_create_action_space(env, config): """Create an action space that can be pickled (or None to leave it for the remote client to sort out). """ return env.action_space
def default_create_action_space(env, config):
"""Create an action space that can be pickled (or None to leave it for the remote client to sort out). """ return env.action_space
("seed " + str(seed)) def render(self, mode='human'): print("render me for " + str(mode)) def close(self): pass def default_create_env(config): """Server env creation factory function""" return ServerEnv(config) def default_create_action_space(env, config):
64
64
44
9
55
andredornas/malmo
MalmoEnv/proxyenv/server.py
Python
default_create_action_space
default_create_action_space
78
82
78
78
d1e7a4335bf6017dbdf83c1ef4cde2cf3fa2764b
bigcode/the-stack
train
163f7adb80e9b920f093e52e
train
function
def handle_client_connection(client_socket, create_env, create_action_space): """handle a client connection """ msg = comms.recv_message(client_socket) config = pickle.loads(msg) print('Received env config {}'.format(repr(config))) if isinstance(config, gym.Env): # Client sent an actual env...
def handle_client_connection(client_socket, create_env, create_action_space):
"""handle a client connection """ msg = comms.recv_message(client_socket) config = pickle.loads(msg) print('Received env config {}'.format(repr(config))) if isinstance(config, gym.Env): # Client sent an actual environment - use it. env = config if isinstance(config, str): ...
(seed)) def render(self, mode='human'): print("render me for " + str(mode)) def close(self): pass def default_create_env(config): """Server env creation factory function""" return ServerEnv(config) def default_create_action_space(env, config): """Create an action space that can...
114
114
381
14
99
andredornas/malmo
MalmoEnv/proxyenv/server.py
Python
handle_client_connection
handle_client_connection
88
140
88
88
962b0367165ae9e1fbd50f85a22dd24f449e1d3c
bigcode/the-stack
train
a3ff18de012f2159991cf7b0
train
class
class ServerEnv(gym.Env): """Dummy server env for testing """ def __init__(self, config): self.config = config self.action_space = gym.spaces.Discrete(2) # TODO self.observation_space = gym.spaces.Box(low=0, high=255, shape=(84, 84, 1)) # TODO self.steps = 0 def reset(sel...
class ServerEnv(gym.Env):
"""Dummy server env for testing """ def __init__(self, config): self.config = config self.action_space = gym.spaces.Discrete(2) # TODO self.observation_space = gym.spaces.Box(low=0, high=255, shape=(84, 84, 1)) # TODO self.steps = 0 def reset(self): print("reset")...
import gym from gym import spaces import cloudpickle import pickle import socket import threading import proxyenv.comms as comms import traceback from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as np BIND_IP = '0.0.0.0' BIND_PORT = 50010 class ServerEnv(gym.Env):
78
78
261
7
70
andredornas/malmo
MalmoEnv/proxyenv/server.py
Python
ServerEnv
ServerEnv
39
70
39
39
7406fdc7e48ce871609940ac5be3273f6fcda93d
bigcode/the-stack
train
edfa0609c8f60f321af73361
train
function
def default_create_env(config): """Server env creation factory function""" return ServerEnv(config)
def default_create_env(config):
"""Server env creation factory function""" return ServerEnv(config)
self.steps} return obs, reward, done, info def seed(self, seed=None): print("seed " + str(seed)) def render(self, mode='human'): print("render me for " + str(mode)) def close(self): pass def default_create_env(config):
64
64
20
6
57
andredornas/malmo
MalmoEnv/proxyenv/server.py
Python
default_create_env
default_create_env
73
75
73
73
e6f0686e927f85aacc3c95ddfece7698179b2531
bigcode/the-stack
train
30ec3102cadd98dd5cb99bd1
train
function
def serve_env(bind_port=BIND_PORT, create_env=default_create_env, create_action_space=default_create_action_space): """Serve proxy openai gym environmets""" print("serve_env") # traceback.print_stack() server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((BIND_IP, bind_port)) s...
def serve_env(bind_port=BIND_PORT, create_env=default_create_env, create_action_space=default_create_action_space):
"""Serve proxy openai gym environmets""" print("serve_env") # traceback.print_stack() server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((BIND_IP, bind_port)) server.listen(5) # max backlog of connections print('proxy env listening on {}:{}'.format(BIND_IP, bind_port)) ...
cloudpickle.dumps(result) comms.send_message(client_socket, reply) else: print('Skip unknown proxy env command!') break env.close() client_socket.close() def serve_env(bind_port=BIND_PORT, create_env=default_create_env, create_action_space=default_create_action_space...
64
64
179
25
39
andredornas/malmo
MalmoEnv/proxyenv/server.py
Python
serve_env
serve_env
143
161
143
143
b4ffe12072195540aefbf90b35608e3d1bd8b961
bigcode/the-stack
train
ee3bee0ca729445243da1b10
train
class
class InputParser(): @staticmethod def parse_input(command): data = [] split_commands = [] options=[] if command and len(command.split()) > 1: split_commands = command.split() main_command = split_commands[0] split_commands = split_commands[1:...
class InputParser(): @staticmethod
def parse_input(command): data = [] split_commands = [] options=[] if command and len(command.split()) > 1: split_commands = command.split() main_command = split_commands[0] split_commands = split_commands[1:] for option in split_comman...
class InputParser(): @staticmethod
8
64
139
8
0
onprem/Pynux
utils/input_parser.py
Python
InputParser
InputParser
1
23
1
3
c6d52a8fb3d29df7a59d6d6591f1169ebec0f2aa
bigcode/the-stack
train
8ed4c96c2350887e7ab30aa6
train
class
class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m'
class bcolors:
HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m'
import sys from colorama import init init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected from termcolor import cprint from pyfiglet import figlet_format from colorama import Fore, Back, Style from getpass import getpass class bcolors:
64
64
81
4
59
north-ner/Knock-Knock
front.py
Python
bcolors
bcolors
20
28
20
20
9259aa94195aeb8c54be46c55f51e64f122f7540
bigcode/the-stack
train
adf459a5e64e167abdac731a
train
function
def firstlast(sequence): return sequence[:1] + sequence[-1:]
def firstlast(sequence):
return sequence[:1] + sequence[-1:]
# DomirScire def firstlast(sequence):
11
64
16
5
5
DomirScire/Python_Workout_Solutions
1to10/09_first_last.py
Python
firstlast
firstlast
3
4
3
3
3ca88e038dbb4a392f929d538cea26811d8989a6
bigcode/the-stack
train
5cc201b0fe0ae035b04294b7
train
function
def _extend_spikes(spike_ids, spike_clusters): """Return all spikes belonging to the clusters containing the specified spikes.""" # We find the spikes belonging to modified clusters. # What are the old clusters that are modified by the assignment? old_spike_clusters = spike_clusters[spike_ids] u...
def _extend_spikes(spike_ids, spike_clusters):
"""Return all spikes belonging to the clusters containing the specified spikes.""" # We find the spikes belonging to modified clusters. # What are the old clusters that are modified by the assignment? old_spike_clusters = spike_clusters[spike_ids] unique_clusters = _unique(old_spike_clusters) ...
ikes_in_clusters, _spikes_per_cluster from ._utils import UpdateInfo from ._history import History from phylib.utils.event import emit logger = logging.getLogger(__name__) #------------------------------------------------------------------------------ # Clustering class #---------------------------------------------...
63
64
151
12
51
fjflores/phy
phy/cluster/clustering.py
Python
_extend_spikes
_extend_spikes
26
37
26
26
4b565f8abf14e3e6a7d3cf5763309a127b52114f
bigcode/the-stack
train
cb99f2730ffcfdec5ca29877
train
class
class Clustering(object): """Handle cluster changes in a set of spikes. Constructor ----------- spike_clusters : array-like Spike-cluster assignments, giving the cluster id of every spike. new_cluster_id : int Cluster id that is not used yet (and not used in the cache if there is o...
class Clustering(object):
"""Handle cluster changes in a set of spikes. Constructor ----------- spike_clusters : array-like Spike-cluster assignments, giving the cluster id of every spike. new_cluster_id : int Cluster id that is not used yet (and not used in the cache if there is one). We need to en...
ike_ids] # Use relative numbers in extended_spike_clusters. _, extended_spike_clusters = np.unique(extended_spike_clusters, return_inverse=True) # Generate new cluster numbers. k = new_spike_clusters.max() + 1 extended_spike_clusters += (k - extended_spike_clusters.min()) # Finally, we concaten...
256
256
3,310
5
250
fjflores/phy
phy/cluster/clustering.py
Python
Clustering
Clustering
98
513
98
98
b017ec0830942f88bdb390b0f3aa3aa805bffa2f
bigcode/the-stack
train
81ae857c71d217d639dbdf7b
train
function
def _extend_assignment(spike_ids, old_spike_clusters, spike_clusters_rel, new_cluster_id): # 1. Add spikes that belong to modified clusters. # 2. Find new cluster ids for all changed clusters. old_spike_clusters = _as_array(old_spike_clusters) spike_ids = _as_array(spike_ids) assert isinstance(spi...
def _extend_assignment(spike_ids, old_spike_clusters, spike_clusters_rel, new_cluster_id): # 1. Add spikes that belong to modified clusters. # 2. Find new cluster ids for all changed clusters.
old_spike_clusters = _as_array(old_spike_clusters) spike_ids = _as_array(spike_ids) assert isinstance(spike_clusters_rel, (list, np.ndarray)) spike_clusters_rel = _as_array(spike_clusters_rel) assert spike_clusters_rel.min() >= 0 # We renumber the new cluster indices. new_spike_clusters = ...
for x, y in pairs]) reorder = np.argsort(concat[:, 0]) concat = concat[reorder, :] return concat[:, 0].astype(np.int64), concat[:, 1].astype(np.int64) def _extend_assignment(spike_ids, old_spike_clusters, spike_clusters_rel, new_cluster_id): # 1. Add spikes that belong to modified clusters. # 2. Fi...
98
98
329
48
50
fjflores/phy
phy/cluster/clustering.py
Python
_extend_assignment
_extend_assignment
49
78
49
52
ed751e2503e95a81ee5f63001e85810e7515efdd
bigcode/the-stack
train
af9bfe0e00081bfcd046da35
train
function
def _concatenate_spike_clusters(*pairs): """Concatenate a list of pairs (spike_ids, spike_clusters).""" pairs = [(_as_array(x), _as_array(y)) for (x, y) in pairs] concat = np.vstack([np.hstack((x[:, None], y[:, None])) for x, y in pairs]) reorder = np.argsort(concat[:, 0]) concat = concat[reorder, :...
def _concatenate_spike_clusters(*pairs):
"""Concatenate a list of pairs (spike_ids, spike_clusters).""" pairs = [(_as_array(x), _as_array(y)) for (x, y) in pairs] concat = np.vstack([np.hstack((x[:, None], y[:, None])) for x, y in pairs]) reorder = np.argsort(concat[:, 0]) concat = concat[reorder, :] return concat[:, 0].astype(np.int64...
_in_clusters(spike_clusters, unique_clusters) # These are the new spikes that need to be reassigned. extended_spike_ids = np.setdiff1d(changed_spike_ids, spike_ids, assume_unique=True) return extended_spike_ids def _concatenate_spike_clusters(*pairs):
64
64
118
10
53
fjflores/phy
phy/cluster/clustering.py
Python
_concatenate_spike_clusters
_concatenate_spike_clusters
40
46
40
40
bb7c632b62efbb530a05f494d5c19dfb6655aa73
bigcode/the-stack
train
d0b6ae7fe2a79ef31473a393
train
function
def _assign_update_info(spike_ids, old_spike_clusters, new_spike_clusters): old_clusters = _unique(old_spike_clusters) new_clusters = _unique(new_spike_clusters) largest_old_cluster = np.bincount(old_spike_clusters).argmax() descendants = list(set(zip(old_spike_clusters, new_spike_clusters))) update...
def _assign_update_info(spike_ids, old_spike_clusters, new_spike_clusters):
old_clusters = _unique(old_spike_clusters) new_clusters = _unique(new_spike_clusters) largest_old_cluster = np.bincount(old_spike_clusters).argmax() descendants = list(set(zip(old_spike_clusters, new_spike_clusters))) update_info = UpdateInfo( description='assign', spike_ids=list(spi...
# Finally, we concatenate spike_ids and extended_spike_ids. return _concatenate_spike_clusters( (spike_ids, new_spike_clusters), (extended_spike_ids, extended_spike_clusters)) def _assign_update_info(spike_ids, old_spike_clusters, new_spike_clusters):
64
64
138
19
45
fjflores/phy
phy/cluster/clustering.py
Python
_assign_update_info
_assign_update_info
81
95
81
81
cea3c19031630d2e7fc8cbecc860a3315a77a9f0
bigcode/the-stack
train
ef090f7ff533dfa864a4cc41
train
class
class FunctionsCollector(cst.CSTVisitor): METADATA_DEPENDENCIES = (PositionProvider,) path: str = "" def __init__(self) -> None: self.issues: List[CodeQualityIssue] = [] def visit_FunctionDef(self, node: cst.FunctionDef) -> None: return_is_annotated = node.returns is not None i...
class FunctionsCollector(cst.CSTVisitor):
METADATA_DEPENDENCIES = (PositionProvider,) path: str = "" def __init__(self) -> None: self.issues: List[CodeQualityIssue] = [] def visit_FunctionDef(self, node: cst.FunctionDef) -> None: return_is_annotated = node.returns is not None if not return_is_annotated: cod...
category": self.category, "detail_message": self.detail_message, "line": self.line, "line_end": self.line_end, "column": self.column, "column_end": self.column_end, "path": self.path, } class FunctionsCollector(cst.CSTVisitor):
64
64
162
9
55
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
FunctionsCollector
FunctionsCollector
268
286
268
268
7f65a08eb9fbfe77ff480f2ff31ac9d24c15e25b
bigcode/the-stack
train
c2f63c5abd9aebe53be4d7f7
train
class
class AnnotationCountCollector(StatisticsCollector): METADATA_DEPENDENCIES = (PositionProvider,) def __init__( self, return_count: int = 0, annotated_return_count: int = 0, globals_count: int = 0, annotated_globals_count: int = 0, parameter_count: int = 0, ...
class AnnotationCountCollector(StatisticsCollector):
METADATA_DEPENDENCIES = (PositionProvider,) def __init__( self, return_count: int = 0, annotated_return_count: int = 0, globals_count: int = 0, annotated_globals_count: int = 0, parameter_count: int = 0, annotated_parameter_count: int = 0, attribu...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import defaultdict from re import compile from typing import Any, Dict, List, Pattern, Sequence import libcst as cst from l...
113
256
1,285
8
105
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
AnnotationCountCollector
AnnotationCountCollector
20
164
20
20
15ecc94e9ad1bbbc4e44bb181311a2280b5facbc
bigcode/the-stack
train
3338b8eb3ba63f1a0d0f4562
train
class
class StrictIssueCollector(StrictCountCollector): METADATA_DEPENDENCIES = (PositionProvider,) path: str = "" issues: List[CodeQualityIssue] = [] def _create_issue(self, node: cst.Module) -> None: file_range = self.get_metadata(PositionProvider, node) code_range = CodeRange(start=file_ra...
class StrictIssueCollector(StrictCountCollector):
METADATA_DEPENDENCIES = (PositionProvider,) path: str = "" issues: List[CodeQualityIssue] = [] def _create_issue(self, node: cst.Module) -> None: file_range = self.get_metadata(PositionProvider, node) code_range = CodeRange(start=file_range.start, end=file_range.start) issue = C...
Issue( code_range, self.path, "PYRE_MISSING_ANNOTATIONS", "This function is missing a return annotation. \ Bodies of unannotated functions are not typechecked by Pyre.", ) self.issues.append(issue) class StrictIssueC...
64
64
149
9
55
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
StrictIssueCollector
StrictIssueCollector
289
304
289
289
8d55a29ff059c744e638ba3104990a044e336fb3
bigcode/the-stack
train
4dddf72bb7fb3f5f9b582646
train
class
class StatisticsCollector(cst.CSTVisitor): def build_json(self) -> Dict[str, int]: return {}
class StatisticsCollector(cst.CSTVisitor):
def build_json(self) -> Dict[str, int]: return {}
the # LICENSE file in the root directory of this source tree. from collections import defaultdict from re import compile from typing import Any, Dict, List, Pattern, Sequence import libcst as cst from libcst.metadata import CodeRange, PositionProvider class StatisticsCollector(cst.CSTVisitor):
64
64
24
9
54
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
StatisticsCollector
StatisticsCollector
15
17
15
15
a049439a965407bdfaafc8d2c2b939a08a075b1c
bigcode/the-stack
train
6702b293d173c98cb8a371c9
train
class
class CountCollector(StatisticsCollector): def __init__(self, regex: str) -> None: self.counts: Dict[str, int] = defaultdict(int) self.regex: Pattern[str] = compile(regex) def visit_Comment(self, node: cst.Comment) -> None: match = self.regex.match(node.value) if match: ...
class CountCollector(StatisticsCollector):
def __init__(self, regex: str) -> None: self.counts: Dict[str, int] = defaultdict(int) self.regex: Pattern[str] = compile(regex) def visit_Comment(self, node: cst.Comment) -> None: match = self.regex.match(node.value) if match: code_group = match.group(1) ...
: cst.ClassDef) -> None: self.class_definition_depth -= 1 def leave_Module(self, original_node: cst.Module) -> None: file_range = self.get_metadata(PositionProvider, original_node) self.line_count = file_range.end.line class CountCollector(StatisticsCollector):
64
64
148
7
56
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
CountCollector
CountCollector
167
184
167
167
3cce4fa64b8aab27285c7f9d39210668d6115f1a
bigcode/the-stack
train
f8647e51f5b84bf9ca1244b7
train
class
class CodeQualityIssue: def __init__( self, code_range: CodeRange, path: str, category: str, message: str ) -> None: self.category: str = category self.detail_message: str = message self.line: int = code_range.start.line self.line_end: int = code_range.end.line se...
class CodeQualityIssue:
def __init__( self, code_range: CodeRange, path: str, category: str, message: str ) -> None: self.category: str = category self.detail_message: str = message self.line: int = code_range.start.line self.line_end: int = code_range.end.line self.column: int = code_ra...
if self.is_unsafe_module(): self.unsafe_count += 1 else: self.strict_count += 1 def build_json(self) -> Dict[str, int]: return {"unsafe_count": self.unsafe_count, "strict_count": self.strict_count} class CodeQualityIssue:
64
64
179
5
59
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
CodeQualityIssue
CodeQualityIssue
244
265
244
244
dbcdc8d575ddc1f98f0170002cc1cbd314bd0c8d
bigcode/the-stack
train
67cda466c848cee9053c2e81
train
class
class FixmeCountCollector(CountCollector): def __init__(self) -> None: super().__init__(r".*# *pyre-fixme(\[(\d* *,? *)*\])?")
class FixmeCountCollector(CountCollector):
def __init__(self) -> None: super().__init__(r".*# *pyre-fixme(\[(\d* *,? *)*\])?")
_group.strip("[] ").split(",") else: codes = ["No Code"] for code in codes: self.counts[code.strip()] += 1 def build_json(self) -> Dict[str, int]: return dict(self.counts) class FixmeCountCollector(CountCollector):
64
64
45
9
55
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
FixmeCountCollector
FixmeCountCollector
187
189
187
187
01a28e2df5f1bb606bba15771659563ca60792aa
bigcode/the-stack
train
1c9730d350fa8517ed638724
train
class
class IgnoreCountCollector(CountCollector): def __init__(self) -> None: super().__init__(r".*# *pyre-ignore(\[(\d* *,? *)*\])?")
class IgnoreCountCollector(CountCollector):
def __init__(self) -> None: super().__init__(r".*# *pyre-ignore(\[(\d* *,? *)*\])?")
, int]: return dict(self.counts) class FixmeCountCollector(CountCollector): def __init__(self) -> None: super().__init__(r".*# *pyre-fixme(\[(\d* *,? *)*\])?") class IgnoreCountCollector(CountCollector):
63
64
42
8
56
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
IgnoreCountCollector
IgnoreCountCollector
192
194
192
192
9397bb96863f9299a51a7caa7858bea79dd63826
bigcode/the-stack
train
c799e4500e48b3c446084196
train
class
class StrictCountCollector(StatisticsCollector): def __init__(self, strict_by_default: bool) -> None: self.is_strict: bool = False self.is_unsafe: bool = False self.strict_count: int = 0 self.unsafe_count: int = 0 self.strict_by_default: bool = strict_by_default self....
class StrictCountCollector(StatisticsCollector):
def __init__(self, strict_by_default: bool) -> None: self.is_strict: bool = False self.is_unsafe: bool = False self.strict_count: int = 0 self.unsafe_count: int = 0 self.strict_by_default: bool = strict_by_default self.unsafe_regex: Pattern[str] = compile(r" ?#+ *pyre...
.counts[code.strip()] += 1 def build_json(self) -> Dict[str, int]: return dict(self.counts) class FixmeCountCollector(CountCollector): def __init__(self) -> None: super().__init__(r".*# *pyre-fixme(\[(\d* *,? *)*\])?") class IgnoreCountCollector(CountCollector): def __init__(self) -> No...
125
126
420
8
118
PulkitMishra/pyre-check
client/statistics_collectors.py
Python
StrictCountCollector
StrictCountCollector
197
241
197
197
258c6ad2d8f68dcf00b4f35f6681e45bff2cffb4
bigcode/the-stack
train
9407857074c3ebcc5140eb3e
train
function
def get_credentials(): try: credentials_path = os.path.dirname(os.path.realpath(__file__)) credentials_file = '.env' cred_dict = None with open(os.path.join(credentials_path, credentials_file), 'r') as creds_file: cred_dict = json.loads(creds_file.read()) retur...
def get_credentials():
try: credentials_path = os.path.dirname(os.path.realpath(__file__)) credentials_file = '.env' cred_dict = None with open(os.path.join(credentials_path, credentials_file), 'r') as creds_file: cred_dict = json.loads(creds_file.read()) return cred_dict except ...
from maltego_trx.transform import DiscoverableTransform log_file_path = os.path.dirname(os.path.realpath(__file__)) log_file_name = 'censys_maltego_transform.log' logging.basicConfig(filename=os.path.join(log_file_path, log_file_name), level=logging.INFO) def get_credentials():
64
64
98
4
60
netsec/censys-maltego
censys/transforms/search_ipv4_to_hash.py
Python
get_credentials
get_credentials
15
29
15
16
ed2f48dc678665ca55a9b159b52f07d3660b3bb4
bigcode/the-stack
train
cc5b2e7f76a406b86b04c8d8
train
class
class search_ipv4_to_hash(DiscoverableTransform): @classmethod def create_entities(cls, request, response): env_config = get_credentials() api_id, api_secret = env_config.get('censys_api_id'), env_config.get('censys_api_secret') ev = request.Value ep = request.Properties ...
class search_ipv4_to_hash(DiscoverableTransform): @classmethod
def create_entities(cls, request, response): env_config = get_credentials() api_id, api_secret = env_config.get('censys_api_id'), env_config.get('censys_api_secret') ev = request.Value ep = request.Properties response = Censys(api_id, api_secret, max_pages=env_config.get('...
as creds_file: cred_dict = json.loads(creds_file.read()) return cred_dict except Exception as e: logging.critical("Please enter your credentials in the .env file in the transforms directory.") raise e class search_ipv4_to_hash(DiscoverableTransform): @classmethod
64
64
116
15
48
netsec/censys-maltego
censys/transforms/search_ipv4_to_hash.py
Python
search_ipv4_to_hash
search_ipv4_to_hash
32
46
32
34
156978a8490d2d11dd5a5c5bd8164920c64d5d95
bigcode/the-stack
train
fff2eaf0658976205740d4a6
train
function
def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray(...
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.sp...
import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr):
108
108
363
7
101
xraymemory/manna
contrib/seeds/generate-seeds.py
Python
name_to_ipv6
name_to_ipv6
45
73
45
45
2e80f2c9f04d5ed5acb45ee10216dfdff6b1eba7
bigcode/the-stack
train
f3ffbb372abbad325d85bd65
train
function
def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port...
def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport ...
]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport):
64
64
141
8
56
xraymemory/manna
contrib/seeds/generate-seeds.py
Python
parse_spec
parse_spec
75
93
75
75
dd000d35b717ae4c4e4581d24307f0f33a3c07dc
bigcode/the-stack
train
21bd08167a9bfb8bc45a072f
train
function
def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List...
def main():
if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed se...
if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main():
84
84
282
3
81
xraymemory/manna
contrib/seeds/generate-seeds.py
Python
main
main
114
134
114
114
61084f5fe08135c13bac4b4b6d5528dad8dbaf9c
bigcode/the-stack
train
09d2686a3814be3b45c036e0
train
function
def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not...
def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first =...
else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport):
64
64
161
13
51
xraymemory/manna
contrib/seeds/generate-seeds.py
Python
process_nodes
process_nodes
95
112
95
95
3dbce44502830f85f28bc4c7456018b89dd95fb8
bigcode/the-stack
train
b5dd40a46c72e4f6ab62af4d
train
class
class KlSlemProductfamilie(KeuzelijstField): """De mogelijke productfamiles.""" naam = 'KlSlemProductfamilie' label = 'Productfamilies' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlSlemProductfamilie' definition = 'De mogelijke productfamiles.' codelist = 'https://wegene...
class KlSlemProductfamilie(KeuzelijstField):
"""De mogelijke productfamiles.""" naam = 'KlSlemProductfamilie' label = 'Productfamilies' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlSlemProductfamilie' definition = 'De mogelijke productfamiles.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/...
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlSlemProductfamilie(KeuzelijstField):
88
105
350
14
73
davidvlaminck/OTLClassPython
src/OTLMOW/OTLModel/Datatypes/KlSlemProductfamilie.py
Python
KlSlemProductfamilie
KlSlemProductfamilie
7
31
7
7
32a471312c71fb982fb6ce0b7fc1136213670c5a
bigcode/the-stack
train
dc213178fba49e6023ca56e2
train
class
class RepeatLabelAgent(Agent): @staticmethod def add_cmdline_args(argparser): group = argparser.add_argument_group('RepeatLabel Arguments') group.add_argument('--return_one_random_answer', type='bool', default=True, help='return one answer from the set of labels') ...
class RepeatLabelAgent(Agent): @staticmethod
def add_cmdline_args(argparser): group = argparser.add_argument_group('RepeatLabel Arguments') group.add_argument('--return_one_random_answer', type='bool', default=True, help='return one answer from the set of labels') group.add_argument('--cant_answer_percent', t...
text_candidates`` field with up to a hundred randomly selected candidates (the first text candidate is the selected label). Options: ``returnOneRandomAnswer`` -- default ``True``, set to ``False`` to instead reply with all labels joined by commas. ``cantAnswerPercent`` -- default ``0``, set value in rang...
114
114
380
11
102
markr-fu-berlin/ParlAI
parlai/agents/repeat_label/repeat_label.py
Python
RepeatLabelAgent
RepeatLabelAgent
29
68
29
30
1a04d63210ad7c01cee6e04fb311e382563ba3f3
bigcode/the-stack
train
9ff8871ceb7c16b0881877f3
train
class
class QtumCashCreateEthOpCodeTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def assert_address_with_value_in_unspents(self, address, value): for unspent ...
class QtumCashCreateEthOpCodeTest(BitcoinTestFramework):
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def assert_address_with_value_in_unspents(self, address, value): for unspent in self.node.listunspent(): if unspent['addre...
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.qtumcash import * from test_framework.address import * class QtumCashCreateEthOpCodeTest(BitcoinTestFrame...
64
256
3,149
14
50
qtumcashproject/qtumcash
test/functional/qtumcash_create_eth_op_code.py
Python
QtumCashCreateEthOpCodeTest
QtumCashCreateEthOpCodeTest
11
183
11
11
ddc26d63396ebdcd30fb33182f8799fc4a9a9f57
bigcode/the-stack
train
d11b0480bf7693e3c36e0759
train
class
class SimpleJwt(JwtAuthBase): """Authentication class to use when the jwt is provided by some other external method.""" def __init__(self, jwt): super().__init__() self._jwt = jwt def generate_jwt(self): raise Exception("SimpleJwt cannnot generate a new jwt")
class SimpleJwt(JwtAuthBase):
"""Authentication class to use when the jwt is provided by some other external method.""" def __init__(self, jwt): super().__init__() self._jwt = jwt def generate_jwt(self): raise Exception("SimpleJwt cannnot generate a new jwt")
']) return exp > time.time() def __call__(self, r): """This method implements the AuthBase super class. The requests library calls this method for every request""" r.headers['Authorization'] = "Bearer {}".format(self.jwt) return r class SimpleJwt(JwtAuthBase):
64
64
68
8
55
DouglasConnect/edelweiss-data-python
edelweiss_data/server.py
Python
SimpleJwt
SimpleJwt
47
54
47
47
3baa048f8d76433c889d01455bca5e33dff27d3d
bigcode/the-stack
train
c7f8f5a087bcca31ed3fd4e3
train
class
class EdelweissHttpError(requests.exceptions.HTTPError): """An HTTP error occurred""" def __init__(self, error_type, *args, **kwargs): self.error_type = error_type return super().__init__(*args, **kwargs)
class EdelweissHttpError(requests.exceptions.HTTPError):
"""An HTTP error occurred""" def __init__(self, error_type, *args, **kwargs): self.error_type = error_type return super().__init__(*args, **kwargs)
exp': int(time.time()) + 3600, self._email_claim: self._email, } jwt = api_jwt.encode(claims, 'secret', algorithm='HS256') return str(jwt, 'utf-8') class EdelweissHttpError(requests.exceptions.HTTPError):
64
64
54
12
52
DouglasConnect/edelweiss-data-python
edelweiss_data/server.py
Python
EdelweissHttpError
EdelweissHttpError
197
202
197
197
5d36897bc2e3a139f176ae5f40b0a37c4ba2ceaa
bigcode/the-stack
train
c8c88cadfc8aa26698b86abf
train
class
class JwtAuthBase(requests.auth.AuthBase, metaclass=abc.ABCMeta): """Abstract base class for authentication by a jwt. This implements the __call__ method, making it compatible with requests library""" def __init__(self): super().__init__() self._jwt = None @abc.abstractmethod d...
class JwtAuthBase(requests.auth.AuthBase, metaclass=abc.ABCMeta):
"""Abstract base class for authentication by a jwt. This implements the __call__ method, making it compatible with requests library""" def __init__(self): super().__init__() self._jwt = None @abc.abstractmethod def generate_jwt(self): """child classes should implement t...
requests import pathlib # There are a few different libraries called jwt, so python can get confused which one to import. # But api_jwt only exists in one library, so this style import makes it unambiguous. from jwt import api_jwt class JwtAuthBase(requests.auth.AuthBase, metaclass=abc.ABCMeta):
71
71
239
18
52
DouglasConnect/edelweiss-data-python
edelweiss_data/server.py
Python
JwtAuthBase
JwtAuthBase
16
45
16
16
5d1c42392208082c0ae96e4a1de3c026b660b14c
bigcode/the-stack
train
888978634e4262a2e04da10f
train
class
class Server: def __init__(self, base_url): self.base_url = base_url self.auth = None def _absolute_url(self, route): return urllib.parse.urljoin(self.base_url, route) def authenticate(self, *args, development:bool=False, jwt=None, **kwargs): if development: ...
class Server:
def __init__(self, base_url): self.base_url = base_url self.auth = None def _absolute_url(self, route): return urllib.parse.urljoin(self.base_url, route) def authenticate(self, *args, development:bool=False, jwt=None, **kwargs): if development: self.aut...
class DevJwt(JwtAuthBase): """Authentication to be used in development only. Creates a self-signed jwt without going to a remote identity provider. This is helpful when the dev server is configured to accept self-signed jwt""" def __init__(self, email : str="user@example.com", ...
228
228
760
3
225
DouglasConnect/edelweiss-data-python
edelweiss_data/server.py
Python
Server
Server
204
291
204
204
cc1773040fe637ab82c82841ab2fdb4543c0e1bf
bigcode/the-stack
train