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
0706fa6e1b9921559a7ac3bf
train
class
class AdminSettings(object): """NOTE: This class is auto generated by the swagger code generator program. from tb_rest_client.api_client import ApiClient Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the valu...
class AdminSettings(object):
"""NOTE: This class is auto generated by the swagger code generator program. from tb_rest_client.api_client import ApiClient Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. at...
# coding: utf-8 """ ThingsBoard REST API ThingsBoard Professional Edition IoT platform REST API documentation. # noqa: E501 OpenAPI spec version: 3.3.3PAAS-RC1 Contact: info@thingsboard.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F40...
96
256
1,184
5
90
samson0v/python_tb_rest_client
tb_rest_client/models/models_pe/admin_settings.py
Python
AdminSettings
AdminSettings
18
192
18
18
6da1770964c20ddec4f3c8f97314802efb8450c7
bigcode/the-stack
train
56989e12cef7a1edcabff513
train
function
def random(n=1, category=None): got = names(category) if got: shuffle(got) if n == 1: return choice(got) return got[:n]
def random(n=1, category=None):
got = names(category) if got: shuffle(got) if n == 1: return choice(got) return got[:n]
names: acc |= names return acc def names(category=None): if not category: category = default() if category == ':all': return list(all()) category = category.replace('/', ' ') return list(data['names'][category]) def random(n=1, category=None):
64
64
43
9
55
ask/metasyntactic
metasyntactic/themes/discworld.py
Python
random
random
185
191
185
185
09c2108bda56b0354851fd2460127741a14d5a90
bigcode/the-stack
train
20e863c92526819ebdd2d702
train
function
def all(): acc = set() for category, names in iteritems(data['names']): if names: acc |= names return acc
def all():
acc = set() for category, names in iteritems(data['names']): if names: acc |= names return acc
parse_data from random import choice, shuffle from six import iteritems data = parse_data(DATA) def default(): try: if 'default' in data: return data['default'][0] except (KeyError, IndexError): pass return 'en' def all():
64
64
33
3
61
ask/metasyntactic
metasyntactic/themes/discworld.py
Python
all
all
168
173
168
168
1370b616a3e749a2613201b5d82ae1eace3f4862
bigcode/the-stack
train
0357ec6c5b76b22ecebfd916
train
function
def default(): try: if 'default' in data: return data['default'][0] except (KeyError, IndexError): pass return 'en'
def default():
try: if 'default' in data: return data['default'][0] except (KeyError, IndexError): pass return 'en'
sto_helit klatch quirm ramtops uberwald djelibeybi ephebe genua llamedos agatean_empire xxxx\ ''' from metasyntactic.base import parse_data from random import choice, shuffle from six import iteritems data = parse_data(DATA) def default():
64
64
39
3
61
ask/metasyntactic
metasyntactic/themes/discworld.py
Python
default
default
159
165
159
159
de1f1db47b2e6ab7676004d6606c8a1336fc655b
bigcode/the-stack
train
844b83d8aea3a5182e2ad549
train
function
def categories(): return set(data['names'])
def categories():
return set(data['names'])
()) category = category.replace('/', ' ') return list(data['names'][category]) def random(n=1, category=None): got = names(category) if got: shuffle(got) if n == 1: return choice(got) return got[:n] def categories():
64
64
10
3
61
ask/metasyntactic
metasyntactic/themes/discworld.py
Python
categories
categories
193
194
193
193
e8671bafcd4aa9c155fd53b7d7c48df540dd6057
bigcode/the-stack
train
6f82874cc6c5a13f63597253
train
function
def names(category=None): if not category: category = default() if category == ':all': return list(all()) category = category.replace('/', ' ') return list(data['names'][category])
def names(category=None):
if not category: category = default() if category == ':all': return list(all()) category = category.replace('/', ' ') return list(data['names'][category])
: return data['default'][0] except (KeyError, IndexError): pass return 'en' def all(): acc = set() for category, names in iteritems(data['names']): if names: acc |= names return acc def names(category=None):
64
64
44
5
58
ask/metasyntactic
metasyntactic/themes/discworld.py
Python
names
names
176
182
176
176
a039400f5af3c7ad24a835d73d56774586ee04f4
bigcode/the-stack
train
0d714000c3e36164b00b99f7
train
function
@pytest.mark.version('>=2.5') @pytest.mark.xfail def test_1(db_1): pytest.fail("Test not IMPLEMENTED")
@pytest.mark.version('>=2.5') @pytest.mark.xfail def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
python_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ 2019-03-01 00:00:00 """ @pytest.mark.version('>=2.5') @pytest.mark.xfail def test_1(db_1):
64
64
31
22
42
reevespaul/firebird-qa
tests/bugs/core_6108_test.py
Python
test_1
test_1
56
59
56
58
afea37c25457165c3f450573e7701abbef22c1ed
bigcode/the-stack
train
857bb47f5f6ca9f4183f77d2
train
class
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Testings', '0001_initial'), ] operations = [ migrations.AddField( model_name='keyword', name='user', field=mo...
class Migration(migrations.Migration):
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Testings', '0001_initial'), ] operations = [ migrations.AddField( model_name='keyword', name='user', field=models.ForeignKey(on_delete=django.db.mode...
: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-21 22:37 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
64
64
83
7
56
ulibn/BlueXolo
apps/Testings/migrations/0002_keyword_user.py
Python
Migration
Migration
10
25
10
11
f12e13e874ecc152ac3e4f0ec35d12476002eed5
bigcode/the-stack
train
acd73caa221bdd9fc22cc843
train
function
def load_cipher(parser): obj = b64(parser) return obj
def load_cipher(parser):
obj = b64(parser) return obj
encrypt", help="Encodethe message") enc.add_argument("--message", "-m", help="The Message") # Decoding dec = sp.add_parser("decrypt", help="Decode the message") dec.add_argument("--message", "-m", help="The Message") def load_cipher(parser):
64
64
16
5
59
fossbrandon/Crypto
crypto/ciphers/base64/__init__.py
Python
load_cipher
load_cipher
19
21
19
19
f6fb518536c16d98efa81165dd762631ce5db373
bigcode/the-stack
train
3b47bedec80f98e4bf228922
train
function
def load_args(subparser): parser = subparser.add_parser('base64', help='Base64 Encoding') sp = parser.add_subparsers(dest="Action", required=True) info = sp.add_parser("info", help="Give details about the cipher") # Encoding enc = sp.add_parser("encrypt", help="Encodethe message") enc.add_argum...
def load_args(subparser):
parser = subparser.add_parser('base64', help='Base64 Encoding') sp = parser.add_subparsers(dest="Action", required=True) info = sp.add_parser("info", help="Give details about the cipher") # Encoding enc = sp.add_parser("encrypt", help="Encodethe message") enc.add_argument("--message", "-m", hel...
from crypto import __version__ from .base64 import b64 def load_args(subparser):
20
64
125
6
13
fossbrandon/Crypto
crypto/ciphers/base64/__init__.py
Python
load_args
load_args
5
16
5
5
0a560dfb476f3e0ae06640d34e59493d5cf75b58
bigcode/the-stack
train
211b197f817fe84fac2a440d
train
class
class Tweet(models.Model): text=models.CharField(max_length=140,help_text="Please enter a tweet") owner=models.ForeignKey('auth.User',related_name='tweets',on_delete=models.CASCADE) is_public = models.BooleanField(default=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=...
class Tweet(models.Model):
text=models.CharField(max_length=140,help_text="Please enter a tweet") owner=models.ForeignKey('auth.User',related_name='tweets',on_delete=models.CASCADE) is_public = models.BooleanField(default=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) m...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Tweet(models.Model):
25
64
160
5
20
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
Tweet
Tweet
4
15
4
4
3912259d742c5f28b3286dc6378d55f814005f31
bigcode/the-stack
train
73a80134234f6c7c896d156c
train
class
class Follow(models.Model): user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE) target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return s...
class Follow(models.Model):
user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE) target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user)+"->"+str(self.t...
', on_delete=models.CASCADE) def __str__(self): return self.tweet.text class Comment(Tweet): parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(s...
64
64
94
5
58
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
Follow
Follow
36
45
36
36
431048a0601a282d9050a310d4b23181b0feef97
bigcode/the-stack
train
3085da516fceea8d7eec50a5
train
class
class Comment(Tweet): parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.text
class Comment(Tweet):
parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.text
.Model): tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=models.CASCADE) ...
64
64
38
5
58
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
Comment
Comment
28
34
28
28
39bcbdc8bd273fb154c5c4e93d06d5caf8f8d512
bigcode/the-stack
train
636676a7f74632b11893d152
train
class
class Like(models.Model): tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=mod...
class Like(models.Model):
tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=models.CASCADE) def __s...
, blank=False, editable=False) likes_count = models.IntegerField(default=0, null=False, blank=False, editable=False) comments_count = models.IntegerField(default=0, null=False, blank=False, editable=False) def __str__(self): return self.text class Like(models.Model):
64
64
62
5
58
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
Like
Like
17
26
17
17
3568ca7cfa5d4a6290474de9b9c3e11b41ea2c52
bigcode/the-stack
train
ae5426bd9e8fcbd37d11f2df
train
class
class UserFollower(models.Model): username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE) followers = models.ManyToManyField('auth.User', related_name='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str...
class UserFollower(models.Model):
username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE) followers = models.ManyToManyField('auth.User', related_name='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str__(self): return str(self....
# class PublicTimeLine(models.Model): # username=models.ForeignKey('auth.User',related_name='public_timeline',on_delete=models.CASCADE) # public_tweet = models.ForeignKey('Tweet', # related_name='public_tweet', # on_delete=models.CASCADE) class Use...
64
64
98
6
58
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
UserFollower
UserFollower
59
67
59
59
e5a3b91b2e106206fa160f00edaefae1165ae143
bigcode/the-stack
train
b7cd9ea75bde465a7c4701f1
train
class
class HashTag(Tweet): name=models.CharField(max_length=10,unique=True) tweet=models.ManyToManyField(Tweet,related_name='hastag') def __str__(self): return self.name class Meta: db_table='hashtag'
class HashTag(Tweet):
name=models.CharField(max_length=10,unique=True) tweet=models.ManyToManyField(Tweet,related_name='hastag') def __str__(self): return self.name class Meta: db_table='hashtag'
='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str__(self): return str(self.username)+"->"+str(self.followers) class Meta: db_table='user_follower' class HashTag(Tweet):
63
64
59
6
57
abhishekzgithub/tweet-django
tweetme/core/models.py
Python
HashTag
HashTag
70
76
70
70
488ec79d016cbb7cfeb1bd7cd3389155760ceea4
bigcode/the-stack
train
2001d5980fdaab195b1a65d7
train
class
class SamplingsApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() ...
class SamplingsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = ap...
# coding: utf-8 """ Lightly API Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@lightly...
149
256
1,252
6
142
Tekrific/lightly
lightly/openapi_generated/swagger_client/api/samplings_api.py
Python
SamplingsApi
SamplingsApi
24
149
24
24
411e16e8561cbe9f08b6ca4d784ecad584cd6fd7
bigcode/the-stack
train
f6757eda7b6c374d8ca1cf7b
train
class
class Find(RelationCommand): def __init__(self, connection, relation): super().__init__(connection) self.relation = relation def execute(self): try: json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute() return rel.Relation(json_o...
class Find(RelationCommand):
def __init__(self, connection, relation): super().__init__(connection) self.relation = relation def execute(self): try: json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute() return rel.Relation(json_obj) except RequestErro...
.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.relation.relation_command import RelationCommand from pyopenproject.model impo...
64
64
98
6
57
webu/pyopenproject
pyopenproject/business/services/command/relation/find.py
Python
Find
Find
8
19
8
9
a332c9dd8be5892637a86e9c312f3e2d6fa59164
bigcode/the-stack
train
dd7f60552c706676bdffdb00
train
class
class TrackingNodeSerializer(serializers.ModelSerializer): class Meta: model = models.TrackingNode fields = ['id', 'date_created', 'tg_chat_id', 'camera_url', 'time_range_start', 'time_range_finish'] read_only_fields = ('date_created',)
class TrackingNodeSerializer(serializers.ModelSerializer):
class Meta: model = models.TrackingNode fields = ['id', 'date_created', 'tg_chat_id', 'camera_url', 'time_range_start', 'time_range_finish'] read_only_fields = ('date_created',)
" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """DRF serializers.""" from rest_framework import ...
64
64
59
8
55
kevromster/GoEat
backend/goeat/serializers.py
Python
TrackingNodeSerializer
TrackingNodeSerializer
22
26
22
22
e688f46d72d87188d47370ed06b5271b4d83e353
bigcode/the-stack
train
42523274ddb3f14edc043dd1
train
function
async def test_begin_reassignment(subscription_state): subscription_state.subscribe({"tp1", "tp2"}) subscription_state.unsubscribe() # After unsubscribe we should not fail begin_reassignment, just ignore it subscription_state.begin_reassignment()
async def test_begin_reassignment(subscription_state):
subscription_state.subscribe({"tp1", "tp2"}) subscription_state.unsubscribe() # After unsubscribe we should not fail begin_reassignment, just ignore it subscription_state.begin_reassignment()
assigned_state(tp2) tp_state = subscription_state._assigned_state(tp1) assert tp_state is not None assert repr(tp_state) == ( "TopicPartitionState<Status=PartitionStatus.AWAITING_RESET" " position=None>" ) async def test_begin_reassignment(subscription_state):
64
64
49
9
55
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_begin_reassignment
test_begin_reassignment
185
190
185
185
5a65731881fecbecc8443cc909b7a1d4ead26d00
bigcode/the-stack
train
ecd2b4088f3c3489d120c29f
train
class
class MockListener(ConsumerRebalanceListener): def on_partitions_revoked(self, revoked): pass def on_partitions_assigned(self, assigned): pass
class MockListener(ConsumerRebalanceListener):
def on_partitions_revoked(self, revoked): pass def on_partitions_assigned(self, assigned): pass
from aiokafka.structs import TopicPartition from aiokafka.abc import ConsumerRebalanceListener # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio @pytest.fixture async def subscription_state(): return SubscriptionState() class MockListener(ConsumerRebalanceListener):
64
64
37
9
55
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
MockListener
MockListener
18
24
18
19
70121d023a243396d2fd8bf70f53e2e72a7f07d2
bigcode/the-stack
train
e8a505f200d2080d47041248
train
function
async def test_assigned_partitions(subscription_state): assert subscription_state.assigned_partitions() == set() subscription_state.subscribe(topics={"tp1"}) assert subscription_state.assigned_partitions() == set() assignment = {TopicPartition("tp1", 0)} subscription_state.assign_from_subscribed(ass...
async def test_assigned_partitions(subscription_state):
assert subscription_state.assigned_partitions() == set() subscription_state.subscribe(topics={"tp1"}) assert subscription_state.assigned_partitions() == set() assignment = {TopicPartition("tp1", 0)} subscription_state.assign_from_subscribed(assignment) assert subscription_state.assigned_partitio...
.state_value(tp) is not None assert not assignment.state_value(tp).has_valid_position assert assignment.state_value(tp)._position is None subscription_state.seek(tp, 1000) assert assignment.state_value(tp).position == 1000 async def test_assigned_partitions(subscription_state):
64
64
79
10
53
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_assigned_partitions
test_assigned_partitions
148
154
148
148
f8c51a5b0b1a51ecba12dbc6651083e30f28496f
bigcode/the-stack
train
f3b8f674de0ce7a7344ba970
train
function
async def test_seek(subscription_state): tp = TopicPartition("topic1", 0) tp2 = TopicPartition("topic2", 0) subscription_state.assign_from_user({tp, tp2}) assignment = subscription_state.subscription.assignment assert assignment.state_value(tp) is not None assert not assignment.state_value(tp)....
async def test_seek(subscription_state):
tp = TopicPartition("topic1", 0) tp2 = TopicPartition("topic2", 0) subscription_state.assign_from_user({tp, tp2}) assignment = subscription_state.subscription.assignment assert assignment.state_value(tp) is not None assert not assignment.state_value(tp).has_valid_position assert assignment....
subscription_state.unsubscribe() assert subscription_state.subscription is None # After unsubscribe you can change the type to say pattern. subscription_state.subscribe_pattern(re.compile("pattern")) subscription_state.subscribe_from_pattern({"tp33"}) assert subscription_state.subscription i...
64
64
109
7
56
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_seek
test_seek
133
145
133
133
a642f23ca357e75428a8d261aa907b7726fa0d9c
bigcode/the-stack
train
3f5163498764556207c2b015
train
function
async def test_unsubscribe(subscription_state): subscription_state.subscribe({"tp1", "tp2"}) assert subscription_state.subscription is not None subscription_state.unsubscribe() assert subscription_state.subscription is None # After unsubscribe you can change the type to say pattern. subscripti...
async def test_unsubscribe(subscription_state):
subscription_state.subscribe({"tp1", "tp2"}) assert subscription_state.subscription is not None subscription_state.unsubscribe() assert subscription_state.subscription is None # After unsubscribe you can change the type to say pattern. subscription_state.subscribe_pattern(re.compile("pattern")...
ics == {"topic3", "topic4"} new_assignment = subscription_state.subscription.assignment assert new_assignment.tps == new_tps assert assignment is not new_assignment assert assignment.active is False assert assignment.unassign_future.done() is True async def test_unsubscribe(subscription_state):
64
64
85
8
55
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_unsubscribe
test_unsubscribe
119
130
119
119
603e78bd39baaedf03c74a5711fd9ef9370187ef
bigcode/the-stack
train
0559eb9e78cd12c8e069b0bf
train
function
async def test_user_assignment(subscription_state): topic_partitions = { TopicPartition("topic1", 0), TopicPartition("topic1", 1), TopicPartition("topic2", 0) } subscription_state.assign_from_user(topic_partitions) assert subscription_state.subscription is not None assert sub...
async def test_user_assignment(subscription_state):
topic_partitions = { TopicPartition("topic1", 0), TopicPartition("topic1", 1), TopicPartition("topic2", 0) } subscription_state.assign_from_user(topic_partitions) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"topic1", "t...
_listener) assert subscription_state.subscription is None assert subscription_state.subscribed_pattern == pattern # After subscription to a pattern we can't change the subscription until # `unsubscribe` called with pytest.raises(IllegalStateError): subscription_state.subscribe( ...
106
107
358
8
98
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_user_assignment
test_user_assignment
75
116
75
75
e4f5658330129d317515a514b7bcd6882e37fb2a
bigcode/the-stack
train
1099ca84a861c74cdd4a0f25
train
function
async def test_subscribe_topic(subscription_state): mock_listener = MockListener() subscription_state.subscribe({"tp1", "tp2"}, listener=mock_listener) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"tp1", "tp2"} assert subscription_state.subscri...
async def test_subscribe_topic(subscription_state):
mock_listener = MockListener() subscription_state.subscribe({"tp1", "tp2"}, listener=mock_listener) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"tp1", "tp2"} assert subscription_state.subscription.assignment is None assert subscription_sta...
ConsumerRebalanceListener # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio @pytest.fixture async def subscription_state(): return SubscriptionState() class MockListener(ConsumerRebalanceListener): def on_partitions_revoked(self, revoked): pass def on_partitio...
83
83
277
9
73
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_subscribe_topic
test_subscribe_topic
27
54
27
27
d45527eacd7c7e71af7b768c05f2be4989d7a863
bigcode/the-stack
train
55731bdb519a45c820798deb
train
function
async def test_is_assigned(subscription_state): tp1 = TopicPartition("topic", 0) tp2 = TopicPartition("topic", 1) assert not subscription_state.is_assigned(tp1) subscription_state.subscribe({"topic"}) assert not subscription_state.is_assigned(tp1) subscription_state.assign_from_subscribed({tp1})...
async def test_is_assigned(subscription_state):
tp1 = TopicPartition("topic", 0) tp2 = TopicPartition("topic", 1) assert not subscription_state.is_assigned(tp1) subscription_state.subscribe({"topic"}) assert not subscription_state.is_assigned(tp1) subscription_state.assign_from_subscribed({tp1}) assert subscription_state.is_assigned(tp1) ...
_state.subscribe(topics={"tp1"}) assert subscription_state.assigned_partitions() == set() assignment = {TopicPartition("tp1", 0)} subscription_state.assign_from_subscribed(assignment) assert subscription_state.assigned_partitions() == assignment async def test_is_assigned(subscription_state):
64
64
94
9
54
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_is_assigned
test_is_assigned
157
165
157
157
45a4376045c60e9723760081ce6f20d756d262d1
bigcode/the-stack
train
8820704ac8eaca242416a270
train
function
@pytest.fixture async def subscription_state(): return SubscriptionState()
@pytest.fixture async def subscription_state():
return SubscriptionState()
_state import SubscriptionState from aiokafka.errors import IllegalStateError from aiokafka.structs import TopicPartition from aiokafka.abc import ConsumerRebalanceListener # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio @pytest.fixture async def subscription_state():
64
64
13
8
55
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
subscription_state
subscription_state
13
15
13
14
02af6ef7f74e1e7ee894af640f156df2d2e57f9e
bigcode/the-stack
train
88f56f3f9003319e1d5df2f6
train
function
async def test_assigned_state(subscription_state): tp1 = TopicPartition("topic", 0) tp2 = TopicPartition("topic", 1) subscription_state.assign_from_user({tp1}) with pytest.raises(IllegalStateError): subscription_state._assigned_state(tp2) tp_state = subscription_state._assigned_state(tp1) ...
async def test_assigned_state(subscription_state):
tp1 = TopicPartition("topic", 0) tp2 = TopicPartition("topic", 1) subscription_state.assign_from_user({tp1}) with pytest.raises(IllegalStateError): subscription_state._assigned_state(tp2) tp_state = subscription_state._assigned_state(tp1) assert tp_state is not None assert repr(tp...
_assigned(tp1) subscription_state.subscribe({"topic"}) assert not subscription_state.is_assigned(tp1) subscription_state.assign_from_subscribed({tp1}) assert subscription_state.is_assigned(tp1) assert not subscription_state.is_assigned(tp2) async def test_assigned_state(subscription_state):
64
64
111
9
55
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_assigned_state
test_assigned_state
168
182
168
168
f098af4898c54103b7561f0913636c697cee9e55
bigcode/the-stack
train
bf1253cc292b6b681d8d15ba
train
function
async def test_subscribe_pattern(subscription_state): mock_listener = MockListener() pattern = re.compile("^tests-.*$") subscription_state.subscribe_pattern( pattern=pattern, listener=mock_listener) assert subscription_state.subscription is None assert subscription_state.subscribed_pattern ...
async def test_subscribe_pattern(subscription_state):
mock_listener = MockListener() pattern = re.compile("^tests-.*$") subscription_state.subscribe_pattern( pattern=pattern, listener=mock_listener) assert subscription_state.subscription is None assert subscription_state.subscribed_pattern == pattern # After subscription to a pattern we c...
_state.subscription.topics == {"tp1", "tp2", "tp3"} assert old_subsciption is not subscription_state.subscription assert old_subsciption.active is False assert old_subsciption.unsubscribe_future.done() is True async def test_subscribe_pattern(subscription_state):
64
64
138
9
54
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
Python
test_subscribe_pattern
test_subscribe_pattern
57
72
57
57
4bee593cdc8f7cd6a84466900b45acb572043e11
bigcode/the-stack
train
62d1b6f3d61bc45acfa910eb
train
class
class OPMLTestCase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.old_app_logger_level = logging.getLogger( 'rss_temple').getEffectiveLevel() cls.old_django_logger_level = logging.getLogger( 'django').getEffectiveLevel() logging.ge...
class OPMLTestCase(TestCase): @classmethod
def setUpClass(cls): super().setUpClass() cls.old_app_logger_level = logging.getLogger( 'rss_temple').getEffectiveLevel() cls.old_django_logger_level = logging.getLogger( 'django').getEffectiveLevel() logging.getLogger('rss_temple').setLevel(logging.CRITICAL...
import logging import datetime from django.test import TestCase, Client from django.core.management import call_command from api import models class OPMLTestCase(TestCase): @classmethod
40
256
1,186
12
27
murrple-1/rss_temple
rss_temple/api/tests/views/test_opml.py
Python
OPMLTestCase
OPMLTestCase
10
163
10
11
61dbc91ddfe8b44ca2cf66fd99635910147726a5
bigcode/the-stack
train
c1a2d25d5b25a1f7e5c5e52c
train
function
def load_policy_model(model_dir="model/test_nlg_no_warm_up_with_nlu.pkl"): model = torch.load(model_dir) net = Net(state_dim=dialog_config.STATE_DIM, num_actions=dialog_config.SYS_ACTION_CARDINALITY).to(device) net.load_state_dict(model) net.eval() return net
def load_policy_model(model_dir="model/test_nlg_no_warm_up_with_nlu.pkl"):
model = torch.load(model_dir) net = Net(state_dim=dialog_config.STATE_DIM, num_actions=dialog_config.SYS_ACTION_CARDINALITY).to(device) net.load_state_dict(model) net.eval() return net
REINFORCE device = torch.device("cuda" if torch.cuda.is_available() else "cpu") STATE_DIM = dialog_config.STATE_DIM NUM_ACTIONS = dialog_config.SYS_ACTION_CARDINALITY def load_policy_model(model_dir="model/test_nlg_no_warm_up_with_nlu.pkl"):
64
64
70
20
43
qbetterk/user-simulator
simulator/policy/test_rule-base-simulator_RL_policy.py
Python
load_policy_model
load_policy_model
23
28
23
23
5fbfb219b2068103d63ef93123a341dfda79094a
bigcode/the-stack
train
bd44754f8f40978650a28024
train
function
def verify_code_asset_exists_v1(uri_props): bucket_ref = uri_props['Bucket']['Ref'] assert bucket_ref.startswith('AssetParameters')
def verify_code_asset_exists_v1(uri_props):
bucket_ref = uri_props['Bucket']['Ref'] assert bucket_ref.startswith('AssetParameters')
import aws_cdk as cdk CDK_VERSION = 2 except ImportError: pytestmark = pytest.mark.skip( "aws_cdk package needed to run CDK tests.") @pytest.fixture def runner(): return CliRunner() def verify_code_asset_exists_v1(uri_props):
64
64
30
10
54
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
verify_code_asset_exists_v1
verify_code_asset_exists_v1
28
30
28
28
8936643663e4bcfd0447d98146177221d926f7d3
bigcode/the-stack
train
82e4b0bdc3e3c55fc8e4dfc9
train
function
def test_can_package_as_cdk_app(runner, verify_code_asset_exists): # The CDK loading/synth can take a while so we're testing the # various APIs out in one test to cut down on test time. with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdkpackage', project_type...
def test_can_package_as_cdk_app(runner, verify_code_asset_exists): # The CDK loading/synth can take a while so we're testing the # various APIs out in one test to cut down on test time.
with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdkpackage', project_type='cdk-ddb') dirname = os.path.abspath(os.path.join('testcdkpackage', 'infrastructure')) os.chdir(dirname) cdk_app, chalice_...
'testcdk') api_handler = chalice_app.get_function('APIHandler') assert api_handler == chalice_app.get_function('APIHandler') role = chalice_app.get_role('DefaultRole') assert hasattr(role, 'role_name') def test_can_package_as_cdk_app(runner, verify_code_asset_exists): # The CDK load...
101
101
338
48
53
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
test_can_package_as_cdk_app
test_can_package_as_cdk_app
84
111
84
86
782f0901cffed866ccd9d19d90bbb04dae19d762
bigcode/the-stack
train
fd525c04541bf2e038e1afb7
train
function
def test_can_package_managed_layer(runner, verify_code_asset_exists): with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdklayers', project_type='cdk-ddb') project_dir = os.path.abspath('testcdklayers') config_file = os.path.join(project_dir, 'runtime',...
def test_can_package_managed_layer(runner, verify_code_asset_exists):
with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdklayers', project_type='cdk-ddb') project_dir = os.path.abspath('testcdklayers') config_file = os.path.join(project_dir, 'runtime', '.chalice', 'config.json') ...
need to verify that we've replaces the CodUri with the # CDK specific assets. functions = filter_resources( cfn_template, 'AWS::Serverless::Function')[0] verify_code_asset_exists(functions[1]['Properties']['CodeUri']) def test_can_package_managed_layer(runner, verify_code_asset_exis...
70
71
239
15
55
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
test_can_package_managed_layer
test_can_package_managed_layer
114
135
114
114
137e111161c396a53d6d2ee3ecbecc375832e225
bigcode/the-stack
train
d3e4cde4e1b9ffcdbf7ed376
train
function
@pytest.fixture def runner(): return CliRunner()
@pytest.fixture def runner():
return CliRunner()
CDK_VERSION = 1 except ImportError: try: import aws_cdk as cdk CDK_VERSION = 2 except ImportError: pytestmark = pytest.mark.skip( "aws_cdk package needed to run CDK tests.") @pytest.fixture def runner():
63
64
11
6
57
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
runner
runner
23
25
23
24
818788815a9f32372e1588340963baccb7cce752
bigcode/the-stack
train
4341942b6a880a05e643dbac
train
function
def load_chalice_construct(dirname, stack_name='testcdk'): try: sys.path.append(dirname) sys.modules.pop('stacks.chaliceapp', None) sys.modules.pop('stacks', None) import stacks.chaliceapp app = cdk.App() chalice_app = stacks.chaliceapp.ChaliceApp(app, stack_name) ...
def load_chalice_construct(dirname, stack_name='testcdk'):
try: sys.path.append(dirname) sys.modules.pop('stacks.chaliceapp', None) sys.modules.pop('stacks', None) import stacks.chaliceapp app = cdk.App() chalice_app = stacks.chaliceapp.ChaliceApp(app, stack_name) return app, chalice_app.chalice finally: s...
('cdk-') @pytest.fixture def verify_code_asset_exists(): if CDK_VERSION == 1: return verify_code_asset_exists_v1 elif CDK_VERSION == 2: return verify_code_asset_exists_v2 def load_chalice_construct(dirname, stack_name='testcdk'):
64
64
122
14
49
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
load_chalice_construct
load_chalice_construct
48
61
48
48
1efc54e3ba4e56929f03257611d11c6c7f4312ab
bigcode/the-stack
train
05aab2445d82ff1b292edbd9
train
function
def filter_resources(template, resource_type): return [(name, props) for name, props in template['Resources'].items() if props['Type'] == resource_type]
def filter_resources(template, resource_type):
return [(name, props) for name, props in template['Resources'].items() if props['Type'] == resource_type]
.chaliceapp.ChaliceApp(app, stack_name) return app, chalice_app.chalice finally: sys.modules.pop('app', None) sys.modules.pop('stacks', None) sys.path.pop() sys.path_importer_cache.clear() def filter_resources(template, resource_type):
64
64
36
8
56
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
filter_resources
filter_resources
64
66
64
64
17f7e018644d7c0adda6ce9bd3cf8f0644afb6a0
bigcode/the-stack
train
6374167c54d4fa431c5709d1
train
function
def test_cdk_construct_api(runner): # The CDK loading/synth can take a while so we're testing the # various APIs out in one test to cut down on test time. with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdk', project_type='cdk-ddb') dirname = os.path....
def test_cdk_construct_api(runner): # The CDK loading/synth can take a while so we're testing the # various APIs out in one test to cut down on test time.
with runner.isolated_filesystem(): newproj.create_new_project_skeleton( 'testcdk', project_type='cdk-ddb') dirname = os.path.abspath(os.path.join('testcdk', 'infrastructure')) os.chdir(dirname) cdk_app, chalice_app = load_chalice_construct(dirname, 'testcdk') api_...
props) for name, props in template['Resources'].items() if props['Type'] == resource_type] def test_cdk_construct_api(runner): # The CDK loading/synth can take a while so we're testing the # various APIs out in one test to cut down on test time.
64
64
163
41
23
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
test_cdk_construct_api
test_cdk_construct_api
69
81
69
71
6cadc4c84b742aa6997da0cbfd3d0624e8d847da
bigcode/the-stack
train
d89455ec5ea0855d68b56439
train
function
def verify_code_asset_exists_v2(uri_props): bucket_ref = uri_props['Bucket']['Fn::Sub'] # Actual sub value will look something like this: # 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'}, assert bucket_ref.startswith('cdk-')
def verify_code_asset_exists_v2(uri_props):
bucket_ref = uri_props['Bucket']['Fn::Sub'] # Actual sub value will look something like this: # 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'}, assert bucket_ref.startswith('cdk-')
"aws_cdk package needed to run CDK tests.") @pytest.fixture def runner(): return CliRunner() def verify_code_asset_exists_v1(uri_props): bucket_ref = uri_props['Bucket']['Ref'] assert bucket_ref.startswith('AssetParameters') def verify_code_asset_exists_v2(uri_props):
64
64
64
10
54
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
verify_code_asset_exists_v2
verify_code_asset_exists_v2
33
37
33
33
2be413f5de28a47f13899df4bfc74bf3a090e4a1
bigcode/the-stack
train
0bf57fc30ebae70a54cfebe9
train
function
@pytest.fixture def verify_code_asset_exists(): if CDK_VERSION == 1: return verify_code_asset_exists_v1 elif CDK_VERSION == 2: return verify_code_asset_exists_v2
@pytest.fixture def verify_code_asset_exists():
if CDK_VERSION == 1: return verify_code_asset_exists_v1 elif CDK_VERSION == 2: return verify_code_asset_exists_v2
): bucket_ref = uri_props['Bucket']['Fn::Sub'] # Actual sub value will look something like this: # 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'}, assert bucket_ref.startswith('cdk-') @pytest.fixture def verify_code_asset_exists():
64
64
45
9
55
hannes-ucsc/chalice
tests/functional/cdk/test_construct.py
Python
verify_code_asset_exists
verify_code_asset_exists
40
45
40
41
046f2d6f83fc64df781821e24454c24edae196d4
bigcode/the-stack
train
d8bbec4304ce1c7bed94c311
train
class
class _PrettyPrinterBase(object): @contextlib.contextmanager def indent(self, indent): """with statement support for indenting/dedenting.""" self.indentation += indent try: yield finally: self.indentation -= indent @contextlib.contextmanager def ...
class _PrettyPrinterBase(object): @contextlib.contextmanager
def indent(self, indent): """with statement support for indenting/dedenting.""" self.indentation += indent try: yield finally: self.indentation -= indent @contextlib.contextmanager def group(self, indent=0, open='', close=''): """like begin_gr...
but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush() class _PrettyPrinterBase(object): @contextlib.contextmanager
64
64
116
14
50
Granitosaurus/xonsh
xonsh/pretty.py
Python
_PrettyPrinterBase
_PrettyPrinterBase
135
153
135
137
05e641900419cbf2727368d5b9cc0fab2b781ffb
bigcode/the-stack
train
4f5e4fa1d7b0e7000b74f301
train
function
def _get_mro(obj_class): """ Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes. """ if not hasattr(obj_class, '__mro__'): # Old-style class. Mix in object to make a fake new-style class. try: obj_class = type(obj...
def _get_mro(obj_class):
""" Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes. """ if not hasattr(obj_class, '__mro__'): # Old-style class. Mix in object to make a fake new-style class. try: obj_class = type(obj_class.__name__, (obj_cla...
: self.text(close) def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer: self.output_width += data.output(self.output, self.output_width) self.buffer.clear() self.buffer_width = 0 def _get_mro(obj_class):
64
64
159
8
55
Granitosaurus/xonsh
xonsh/pretty.py
Python
_get_mro
_get_mro
289
305
289
289
8df5d9fe1b37ec6793fc736b348b6fc32c046244
bigcode/the-stack
train
5b8192d702e9ed416719d796
train
class
class Text(Printable): def __init__(self): self.objs = [] self.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width...
class Text(Printable):
def __init__(self): self.objs = [] self.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width += width
: # Move the printer over to the regular registry. printer = self.deferred_pprinters.pop(key) self.type_pprinters[cls] = printer return printer class Printable(object): def output(self, stream, output_width): return output_width class Text(Printable):
64
64
78
5
58
Granitosaurus/xonsh
xonsh/pretty.py
Python
Text
Text
406
419
406
407
5a3df38bede241edd3a7f97a875cce445828d823
bigcode/the-stack
train
6b19c7125c8b4adf2622e197
train
function
def _deque_pprint(obj, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(list(obj))
def _deque_pprint(obj, p, cycle):
name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(list(obj))
, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') elif len(obj): p.pretty(list(obj.items())) def _deque_pprint(obj, p, cycle):
63
64
55
11
52
Granitosaurus/xonsh
xonsh/pretty.py
Python
_deque_pprint
_deque_pprint
831
837
831
831
f90af682400aee37915f01bfc82c57037f9e6db0
bigcode/the-stack
train
c21559505d2fe6882f54ed66
train
function
@lazyobject def _deferred_type_pprinters(): dtp = {} for_type_by_name('collections', 'defaultdict', _defaultdict_pprint, dtp=dtp) for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint, dtp=dtp) for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp) for_type_by_name('collection...
@lazyobject def _deferred_type_pprinters():
dtp = {} for_type_by_name('collections', 'defaultdict', _defaultdict_pprint, dtp=dtp) for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint, dtp=dtp) for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp) for_type_by_name('collections', 'Counter', _counter_pprint, dtp=dtp) ...
tp[unicode] = _repr_pprint except NameError: tp[range] = _repr_pprint tp[bytes] = _repr_pprint return tp #: printers for types specified by name @lazyobject def _deferred_type_pprinters():
64
64
116
13
50
Granitosaurus/xonsh
xonsh/pretty.py
Python
_deferred_type_pprinters
_deferred_type_pprinters
767
774
767
768
d7cc2b4ed19725405fc4df9d175dbf6685518751
bigcode/the-stack
train
11938332aa68e7122a024d9f
train
function
def _defaultdict_pprint(obj, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(obj.default_factory) p.text(',') p.breakable() p.pretty(dict(obj))
def _defaultdict_pprint(obj, p, cycle):
name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(obj.default_factory) p.text(',') p.breakable() p.pretty(dict(obj))
for the default singletons _singleton_pprinters = LazyObject(lambda: dict.fromkeys( map(id, [None, True, False, Ellipsis, NotImplemented]), _repr_pprint), globals(), '_singleton_pprinters') def _defaultdi...
64
64
72
12
52
Granitosaurus/xonsh
xonsh/pretty.py
Python
_defaultdict_pprint
_defaultdict_pprint
810
819
810
810
fd72f05387cd309dab49583c82ad231895a078ed
bigcode/the-stack
train
7f4941c50530321ee6ac4fb4
train
class
class GroupQueue(object): def __init__(self, *groups): self.queue = [] for group in groups: self.enq(group) def enq(self, group): depth = group.depth while depth > len(self.queue) - 1: self.queue.append([]) self.queue[depth].append(group) de...
class GroupQueue(object):
def __init__(self, *groups): self.queue = [] for group in groups: self.enq(group) def enq(self, group): depth = group.depth while depth > len(self.queue) - 1: self.queue.append([]) self.queue[depth].append(group) def deq(self): for st...
self.pretty.group_queue.remove(self.group) stream.write(self.obj) return output_width + self.width class Group(Printable): def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False class GroupQueue(object):
64
64
163
5
58
Granitosaurus/xonsh
xonsh/pretty.py
Python
GroupQueue
GroupQueue
452
480
452
453
0a2db1f535db6b7a3f8ae365fd5e7818b53fd55d
bigcode/the-stack
train
70f95aadcdece3f4899b5b84
train
class
class Printable(object): def output(self, stream, output_width): return output_width
class Printable(object):
def output(self, stream, output_width): return output_width
(mod, name) printer = None if key in self.deferred_pprinters: # Move the printer over to the regular registry. printer = self.deferred_pprinters.pop(key) self.type_pprinters[cls] = printer return printer class Printable(object):
64
64
19
4
59
Granitosaurus/xonsh
xonsh/pretty.py
Python
Printable
Printable
400
403
400
401
ff11e3fa441dece1d7f9adf9d9541d3649311ead
bigcode/the-stack
train
8cd2faa1a14ae6267b65dd54
train
function
def _function_pprint(obj, p, cycle): """Base pprint for all functions and builtin functions.""" name = _safe_getattr(obj, '__qualname__', obj.__name__) mod = obj.__module__ if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): name = mod + '.' + name p.text('<function %s>' % name)...
def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions.""" name = _safe_getattr(obj, '__qualname__', obj.__name__) mod = obj.__module__ if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): name = mod + '.' + name p.text('<function %s>' % name)
redirects to the normal repr function.""" # Find newlines and replace them with p.break_() output = repr(obj) for idx,output_line in enumerate(output.splitlines()): if idx: p.break_() p.text(output_line) def _function_pprint(obj, p, cycle):
64
64
86
11
53
Granitosaurus/xonsh
xonsh/pretty.py
Python
_function_pprint
_function_pprint
698
704
698
698
6c60c683ab0598bee2ede138946d4850b83e0a44
bigcode/the-stack
train
dd2b1b6c6f971cf3f919c7d7
train
function
def _ordereddict_pprint(obj, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') elif len(obj): p.pretty(list(obj.items()))
def _ordereddict_pprint(obj, p, cycle):
name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') elif len(obj): p.pretty(list(obj.items()))
with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(obj.default_factory) p.text(',') p.breakable() p.pretty(dict(obj)) def _ordereddict_pprint(obj, p, cycle):
64
64
60
13
51
Granitosaurus/xonsh
xonsh/pretty.py
Python
_ordereddict_pprint
_ordereddict_pprint
822
828
822
822
e9afdcc81ad0bfda52f0395ec5eae8e3f64063fc
bigcode/the-stack
train
d15d03ef26b9ef4ff0cda4b0
train
function
def _set_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sets and frozensets. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: # If the subclass p...
def _set_pprinter_factory(start, end, basetype):
""" Factory that returns a pprint function useful for sets and frozensets. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: # If the subclass provides its own repr, use it instead. ...
in p._enumerate(obj): if idx: p.text(',') p.breakable() p.pretty(x) if len(obj) == 1 and type(obj) is tuple: # Special case for 1-item tuples. p.text(',') p.end_group(step, end) return inner def _set_pprinter_factory(st...
79
79
264
13
65
Granitosaurus/xonsh
xonsh/pretty.py
Python
_set_pprinter_factory
_set_pprinter_factory
557
589
557
557
5945ec548f81e5af6d0fea93f48a5b0e51bb8523
bigcode/the-stack
train
b61fb693cca2d9a8634347f3
train
function
@lazyobject def _baseclass_reprs(): try: br = (object.__repr__, types.InstanceType.__repr__) except AttributeError: # Python 3 br = (object.__repr__,) return br
@lazyobject def _baseclass_reprs():
try: br = (object.__repr__, types.InstanceType.__repr__) except AttributeError: # Python 3 br = (object.__repr__,) return br
_break = True return group for group in stack: group.want_break = True del stack[:] def remove(self, group): try: self.queue[group.depth].remove(group) except ValueError: pass @lazyobject def _baseclass_reprs():
64
64
52
11
52
Granitosaurus/xonsh
xonsh/pretty.py
Python
_baseclass_reprs
_baseclass_reprs
483
489
483
484
5a3cf682bc9063e853495024f23f40be498ec3a7
bigcode/the-stack
train
5ee265340efc76f8a16f4be5
train
function
def _re_pattern_pprint(obj, p, cycle): """The pprint function for regular expression patterns.""" p.text('re.compile(') pattern = repr(obj.pattern) if pattern[:1] in 'uU': pattern = pattern[1:] prefix = 'ur' else: prefix = 'r' pattern = prefix + pattern.replace('\\\\', '\...
def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns.""" p.text('re.compile(') pattern = repr(obj.pattern) if pattern[:1] in 'uU': pattern = pattern[1:] prefix = 'ur' else: prefix = 'r' pattern = prefix + pattern.replace('\\\\', '\\') p.text(pattern) if obj.flag...
The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__thisclass__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>') def _re_pattern_pprint(obj, p, cycle):
63
64
184
12
51
Granitosaurus/xonsh
xonsh/pretty.py
Python
_re_pattern_pprint
_re_pattern_pprint
635
657
635
635
7832ddb61c4e62dccd716e9d51110eb5f30073c7
bigcode/the-stack
train
5246b868b3d53dab4c0c054d
train
class
class RepresentationPrinter(PrettyPrinter): """ Special pretty printer that has a `pretty` method that calls the pretty printer for a python object. This class stores processing data on `self` so you must *never* use this class in a threaded environment. Always lock it or reinstanciate it. ...
class RepresentationPrinter(PrettyPrinter):
""" Special pretty printer that has a `pretty` method that calls the pretty printer for a python object. This class stores processing data on `self` so you must *never* use this class in a threaded environment. Always lock it or reinstanciate it. Instances also have a verbose flag callbac...
_stack.pop() if not group.breakables: self.group_queue.remove(group) if close: self.text(close) def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer: self.output_width += data.output(self.output, self.output_width)...
242
242
808
7
234
Granitosaurus/xonsh
xonsh/pretty.py
Python
RepresentationPrinter
RepresentationPrinter
308
397
308
308
abb4e8a5f12742efd967272998279ce382d57de9
bigcode/the-stack
train
7adb12e967f4c612184e7199
train
function
@lazyobject def _type_pprinters(): #: printers for builtin types tp = { int: _repr_pprint, float: _repr_pprint, str: _repr_pprint, tuple: _seq_pprinter_factory('(', ')', tuple), list: ...
@lazyobject def _type_pprinters(): #: printers for builtin types
tp = { int: _repr_pprint, float: _repr_pprint, str: _repr_pprint, tuple: _seq_pprinter_factory('(', ')', tuple), list: _seq_pprinter_factory('[', ']', list), ...
.__class__.__name__) if obj.__class__.__module__ not in ('exceptions', 'builtins'): name = '%s.%s' % (obj.__class__.__module__, name) step = len(name) + 1 p.begin_group(step, name + '(') for idx, arg in enumerate(getattr(obj, 'args', ())): if idx: p.text(',') p.br...
120
121
404
18
102
Granitosaurus/xonsh
xonsh/pretty.py
Python
_type_pprinters
_type_pprinters
724
764
724
726
315b7691bb01fdb807dfa7351d332dc11ce6f6de
bigcode/the-stack
train
b1ab7c87ee98dafbb3e84c77
train
class
class Breakable(Printable): def __init__(self, seq, width, pretty): self.obj = seq self.width = width self.pretty = pretty self.indentation = pretty.indentation self.group = pretty.group_stack[-1] self.group.breakables.append(self) def output(self, stream, outpu...
class Breakable(Printable):
def __init__(self, seq, width, pretty): self.obj = seq self.width = width self.pretty = pretty self.indentation = pretty.indentation self.group = pretty.group_stack[-1] self.group.breakables.append(self) def output(self, stream, output_width): self.group....
.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width += width class Breakable(Printable):
64
64
144
6
57
Granitosaurus/xonsh
xonsh/pretty.py
Python
Breakable
Breakable
422
441
422
423
ec354266381bf5ea0d49bc98fd74465d1b11cda4
bigcode/the-stack
train
4865e470c67762e5a5deee19
train
class
class PrettyPrinter(_PrettyPrinterBase): """ Baseclass for the `RepresentationPrinter` prettyprinter that is used to generate pretty reprs of objects. Contrary to the `RepresentationPrinter` this printer knows nothing about the default pprinters or the `_repr_pretty_` callback method. """ ...
class PrettyPrinter(_PrettyPrinterBase):
""" Baseclass for the `RepresentationPrinter` prettyprinter that is used to generate pretty reprs of objects. Contrary to the `RepresentationPrinter` this printer knows nothing about the default pprinters or the `_repr_pretty_` callback method. """ def __init__(self, output, max_width=79, ...
Pretty print the object's representation. """ stream = CUnicodeIO() printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() return stream.getvalue() def pprint(obj, verbose=False, max_width=79, newline='\n', max_s...
256
256
974
8
248
Granitosaurus/xonsh
xonsh/pretty.py
Python
PrettyPrinter
PrettyPrinter
156
286
156
156
7a29226fb47bd03ea156539c941d1e5a69808d32
bigcode/the-stack
train
70d43987040d71b6d3906dd3
train
function
def _safe_getattr(obj, attr, default=None): """Safe version of getattr. Same as getattr, but will return ``default`` on any Exception, rather than raising. """ try: return getattr(obj, attr, default) except Exception: return default
def _safe_getattr(obj, attr, default=None):
"""Safe version of getattr. Same as getattr, but will return ``default`` on any Exception, rather than raising. """ try: return getattr(obj, attr, default) except Exception: return default
from xonsh.lazyasd import LazyObject, lazyobject __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter', 'for_type', 'for_type_by_name'] MAX_SEQ_LENGTH = 1000 def _safe_getattr(obj, attr, default=None):
64
64
61
12
51
Granitosaurus/xonsh
xonsh/pretty.py
Python
_safe_getattr
_safe_getattr
98
107
98
98
5593102533dabc7124611f010199613f8c466b22
bigcode/the-stack
train
a3d5fd5d9029c93e99ae2207
train
function
def _dict_pprinter_factory(start, end, basetype=None): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:...
def _dict_pprinter_factory(start, end, basetype=None):
""" Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: # If the subclass provides its own repr, u...
) except Exception: # Sometimes the items don't sort. pass for idx, x in p._enumerate(items): if idx: p.text(',') p.breakable() p.pretty(x) p.end_group(step, end) r...
72
72
242
14
57
Granitosaurus/xonsh
xonsh/pretty.py
Python
_dict_pprinter_factory
_dict_pprinter_factory
592
622
592
592
a4d3dc4243128f79024b71b07f42558037e2d50d
bigcode/the-stack
train
b7bafc252dddc818ba1c334c
train
function
def _counter_pprint(obj, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') elif len(obj): p.pretty(dict(obj))
def _counter_pprint(obj, p, cycle):
name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') elif len(obj): p.pretty(dict(obj))
deque_pprint(obj, p, cycle): name = obj.__class__.__name__ with p.group(len(name) + 1, name + '(', ')'): if cycle: p.text('...') else: p.pretty(list(obj)) def _counter_pprint(obj, p, cycle):
64
64
57
11
53
Granitosaurus/xonsh
xonsh/pretty.py
Python
_counter_pprint
_counter_pprint
840
846
840
840
10c1e674a391b3187edc6298dae36e1796cc17d9
bigcode/the-stack
train
28857e35d41a6a9daa51d28b
train
class
class Group(Printable): def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False
class Group(Printable):
def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False
.group.want_break: stream.write(self.pretty.newline) stream.write(' ' * self.indentation) return self.indentation if not self.group.breakables: self.pretty.group_queue.remove(self.group) stream.write(self.obj) return output_width + self.width class...
64
64
36
5
58
Granitosaurus/xonsh
xonsh/pretty.py
Python
Group
Group
444
449
444
445
725114d925ebac278f26c3c595044f8c8b5995bd
bigcode/the-stack
train
b3fe8483e62e03dbfa75635c
train
function
def _seq_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, and lists. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ !...
def _seq_pprinter_factory(start, end, basetype):
""" Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, and lists. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: # If the subclas...
(key) p.text('=') step = len(key) + 1 p.indentation += step p.pretty(value) p.indentation -= step first = False p.end_group(1, '>') def _seq_pprinter_factory(start, end, basetype):
63
64
210
13
50
Granitosaurus/xonsh
xonsh/pretty.py
Python
_seq_pprinter_factory
_seq_pprinter_factory
530
554
530
530
50ac41527c9693867679bc096c2572812351c7bc
bigcode/the-stack
train
bcd722894a124f9b4564ec23
train
function
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): """ Pretty print the object's representation. """ stream = CUnicodeIO() printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.f...
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
""" Pretty print the object's representation. """ stream = CUnicodeIO() printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() return stream.getvalue()
`` on any Exception, rather than raising. """ try: return getattr(obj, attr, default) except Exception: return default CUnicodeIO = io.StringIO def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
64
64
78
24
39
Granitosaurus/xonsh
xonsh/pretty.py
Python
pretty
pretty
113
121
113
113
40b7ee432ac7123ba1c635c90ef9f2c7ced87bd5
bigcode/the-stack
train
b717ce601e419c573c1c191f
train
function
def _exception_pprint(obj, p, cycle): """Base pprint for all exceptions.""" name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) if obj.__class__.__module__ not in ('exceptions', 'builtins'): name = '%s.%s' % (obj.__class__.__module__, name) step = len(name) + 1 p.begin_grou...
def _exception_pprint(obj, p, cycle):
"""Base pprint for all exceptions.""" name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) if obj.__class__.__module__ not in ('exceptions', 'builtins'): name = '%s.%s' % (obj.__class__.__module__, name) step = len(name) + 1 p.begin_group(step, name + '(') for idx, arg i...
name__', obj.__name__) mod = obj.__module__ if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): name = mod + '.' + name p.text('<function %s>' % name) def _exception_pprint(obj, p, cycle):
64
64
135
11
53
Granitosaurus/xonsh
xonsh/pretty.py
Python
_exception_pprint
_exception_pprint
707
719
707
707
bd8b161466d2f92a5a9e865de8a6b07fba800dbb
bigcode/the-stack
train
2dd72e82deefe97ebf5f3827
train
function
def for_type_by_name(type_module, type_name, func, dtp=None): """ Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. """ if dtp is None: dtp = _deferred_type_pprinters key = (type_module, type_name) oldfunc = dtp.get(key, No...
def for_type_by_name(type_module, type_name, func, dtp=None):
""" Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. """ if dtp is None: dtp = _deferred_type_pprinters key = (type_module, type_name) oldfunc = dtp.get(key, None) if func is not None: # To support easy restora...
typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc def for_type_by_name(type_module, type_name, func, dtp=None):
64
64
126
17
46
Granitosaurus/xonsh
xonsh/pretty.py
Python
for_type_by_name
for_type_by_name
788
800
788
788
e90f9801de851a1cdd7da1bb5658276885c829a8
bigcode/the-stack
train
81277114a92dd67f5abd218c
train
function
def for_type(typ, func): """ Add a pretty printer for a given type. """ oldfunc = _type_pprinters.get(typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc
def for_type(typ, func):
""" Add a pretty printer for a given type. """ oldfunc = _type_pprinters.get(typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc
, dtp=dtp) for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp) for_type_by_name('collections', 'Counter', _counter_pprint, dtp=dtp) return dtp def for_type(typ, func):
64
64
80
8
55
Granitosaurus/xonsh
xonsh/pretty.py
Python
for_type
for_type
777
785
777
777
6d76c97341fb011a50ad6ca08d7311985fd078d8
bigcode/the-stack
train
981b6aea86c5a49e21d82e82
train
function
def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__thisclass__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>')
def _super_pprint(obj, p, cycle):
"""The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__thisclass__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>')
for idx, key in p._enumerate(keys): if idx: p.text(',') p.breakable() p.pretty(key) p.text(': ') p.pretty(obj[key]) p.end_group(1, end) return inner def _super_pprint(obj, p, cycle):
64
64
64
11
52
Granitosaurus/xonsh
xonsh/pretty.py
Python
_super_pprint
_super_pprint
625
632
625
625
16c21a3155adc792511e1662b136c47a96221e30
bigcode/the-stack
train
bf4662c68798f92a4cff4b50
train
function
def _type_pprint(obj, p, cycle): """The pprint for classes and types.""" # Heap allocated types might not have the module attribute, # and others may set it to None. # Checks for a __repr__ override in the metaclass if type(obj).__repr__ is not type.__repr__: _repr_pprint(obj, p, cycle) ...
def _type_pprint(obj, p, cycle):
"""The pprint for classes and types.""" # Heap allocated types might not have the module attribute, # and others may set it to None. # Checks for a __repr__ override in the metaclass if type(obj).__repr__ is not type.__repr__: _repr_pprint(obj, p, cycle) return mod = _safe_geta...
'UNICODE', 'VERBOSE', 'DEBUG'): if obj.flags & getattr(re, flag): if done_one: p.text('|') p.text('re.' + flag) done_one = True p.text(')') def _type_pprint(obj, p, cycle):
63
64
216
11
53
Granitosaurus/xonsh
xonsh/pretty.py
Python
_type_pprint
_type_pprint
660
685
660
660
3a2e4f2878dea3dcc39405867099dd162739c174
bigcode/the-stack
train
9c4584567c4c92ff5cda2d7b
train
function
def _repr_pprint(obj, p, cycle): """A pprint that just redirects to the normal repr function.""" # Find newlines and replace them with p.break_() output = repr(obj) for idx,output_line in enumerate(output.splitlines()): if idx: p.break_() p.text(output_line)
def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function.""" # Find newlines and replace them with p.break_() output = repr(obj) for idx,output_line in enumerate(output.splitlines()): if idx: p.break_() p.text(output_line)
name__ if not isinstance(name, str): name = '<unknown type>' if mod in (None, '__builtin__', 'builtins', 'exceptions'): p.text(name) else: p.text(mod + '.' + name) def _repr_pprint(obj, p, cycle):
64
64
70
11
53
Granitosaurus/xonsh
xonsh/pretty.py
Python
_repr_pprint
_repr_pprint
688
695
688
688
419172a7a0ed8c77c39648c05d2ab5c878c932ad
bigcode/the-stack
train
43c252e1c80cc241d8391da6
train
function
def _default_pprint(obj, p, cycle): """ The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = _safe_getattr(obj, '__class__', None) or type(obj) if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs: # A user-pro...
def _default_pprint(obj, p, cycle):
""" The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = _safe_getattr(obj, '__class__', None) or type(obj) if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs: # A user-provided repr. Find newlines and replac...
try: self.queue[group.depth].remove(group) except ValueError: pass @lazyobject def _baseclass_reprs(): try: br = (object.__repr__, types.InstanceType.__repr__) except AttributeError: # Python 3 br = (object.__repr__,) return br def _default_pprint(obj, p, ...
82
82
276
11
70
Granitosaurus/xonsh
xonsh/pretty.py
Python
_default_pprint
_default_pprint
492
527
492
492
f181b9820826f678873489c151f49e9a138a3163
bigcode/the-stack
train
f7537024c61defc222d6d517
train
function
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() sys.stdout.write(n...
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
""" Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
CUnicodeIO() printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() return stream.getvalue() def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
64
64
81
24
40
Granitosaurus/xonsh
xonsh/pretty.py
Python
pprint
pprint
124
132
124
124
534eb0930ac91f6d65bf2c4bb8558f8cbe0a5662
bigcode/the-stack
train
f3dd99ffb112e0fcd6d8aab4
train
class
class Joint: def __init__(self, servo: IServo, **kwargs): self._servo = servo self._angle = 0 self.reverse_direction = False self.min_angle = 0 self.max_angle = 180 self._instant_move = True for key, value in kwargs.items(): if key == "angle": ...
class Joint:
def __init__(self, servo: IServo, **kwargs): self._servo = servo self._angle = 0 self.reverse_direction = False self.min_angle = 0 self.max_angle = 180 self._instant_move = True for key, value in kwargs.items(): if key == "angle": ...
from iservo import IServo class Joint:
10
97
324
3
6
Noardewyn/spider-robot
joint.py
Python
Joint
Joint
4
54
4
4
61e6fd8265f6fd45b90b3592d09af8896dbfc88f
bigcode/the-stack
train
6915d3e40e203b92734cc0aa
train
class
class GetUserSPNs: @staticmethod def printTable(items, header): colLen = [] for i, col in enumerate(header): rowMaxLen = max([len(row[i]) for row in items]) colLen.append(max(rowMaxLen, len(col))) outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width...
class GetUserSPNs: @staticmethod
def printTable(items, header): colLen = [] for i, col in enumerate(header): rowMaxLen = max([len(row[i]) for row in items]) colLen.append(max(rowMaxLen, len(col))) outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)]) # Pr...
# [X] Improve the search filter, we have to specify we don't want machine accounts in the answer # (play with userAccountControl) # from __future__ import division from __future__ import print_function import argparse import logging import os import sys from datetime import datetime from binascii import hexlify, ...
256
256
3,595
10
245
jsherwood0/impacket
examples/GetUserSPNs.py
Python
GetUserSPNs
GetUserSPNs
52
381
52
53
41758b5efcaa3e796e949be5c34106a314fdfc0e
bigcode/the-stack
train
6044ab827837adcb2a0ace9b
train
function
@login_required def sip_detail(request, pk): ip = InformationPackage.objects.get(pk=pk) if not ip.uid: context = {"ip": ip} return render(request, 'management/checkout.html', context=context) return upload_step1(request, pk)
@login_required def sip_detail(request, pk):
ip = InformationPackage.objects.get(pk=pk) if not ip.uid: context = {"ip": ip} return render(request, 'management/checkout.html', context=context) return upload_step1(request, pk)
_work } return render(request, 'management/iptable.html', context=context) @login_required def index(request): template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request)) @login_required def sip_detail(request, p...
64
64
58
10
54
eark-project/access_dipcreator
management/views.py
Python
sip_detail
sip_detail
65
71
65
66
9c274211af12974673d2ab973895a715025f41cb
bigcode/the-stack
train
67c55ccf7551ff0677770580
train
function
def upload_aip(ip_work_dir, upload_path, f): print("Upload file '%s' to working directory: %s" % (f, upload_path)) if not os.path.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: ...
def upload_aip(ip_work_dir, upload_path, f):
print("Upload file '%s' to working directory: %s" % (f, upload_path)) if not os.path.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: for chunk in f.chunks(): d...
, pk): ip = InformationPackage.objects.get(pk=pk) if not ip.uid: context = {"ip": ip} return render(request, 'management/checkout.html', context=context) return upload_step1(request, pk) def upload_aip(ip_work_dir, upload_path, f):
64
64
169
13
51
eark-project/access_dipcreator
management/views.py
Python
upload_aip
upload_aip
74
87
74
74
22d988e4419a4d464fcd51bb5e0b9d928c799299
bigcode/the-stack
train
4bd87b4f7f3e4bbae9bcdaa3
train
function
@login_required def index(request): template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request))
@login_required def index(request):
template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request))
render from django_tables2 import RequestConfig from uuid import uuid4 import logging from submission.views import upload_step1 from util.djangoutils import get_user_api_token logger = logging.getLogger(__name__) from django.utils.translation import ugettext_lazy as _ @login_required def index(request):
63
64
36
7
56
eark-project/access_dipcreator
management/views.py
Python
index
index
34
39
34
35
7444edd5b7f07775cab3696a9bbd1a1c98565622
bigcode/the-stack
train
49a53101917b961559977564
train
class
class InformationPackageDetail(DetailView): """ Information Package Detail View """ model = InformationPackage context_object_name = 'ip' template_name = 'management/detail.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(InformationPacka...
class InformationPackageDetail(DetailView):
""" Information Package Detail View """ model = InformationPackage context_object_name = 'ip' template_name = 'management/detail.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(InformationPackageDetail, self).dispatch(*args, **kwargs) ...
.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) destination.close() class InformationPackageDetail(DetailView):
64
64
156
8
56
eark-project/access_dipcreator
management/views.py
Python
InformationPackageDetail
InformationPackageDetail
244
263
244
244
e8e05664e1ecf724929ae4ba16c17ad5a71e4c64
bigcode/the-stack
train
e4a2b1fdf9d4f8a1c362bafc
train
function
@login_required def checkout(request, identifier): ip = InformationPackage.objects.get(identifier=identifier) uid = None if not ip.uid: uid = str(uuid4()) ip.uid = uid ip.work_dir = os.path.join(config_path_work, uid) template = loader.get_template('management/checkout_confirm.ht...
@login_required def checkout(request, identifier):
ip = InformationPackage.objects.get(identifier=identifier) uid = None if not ip.uid: uid = str(uuid4()) ip.uid = uid ip.work_dir = os.path.join(config_path_work, uid) template = loader.get_template('management/checkout_confirm.html') from config.configuration import django_ba...
delete(request, pk): ip = InformationPackage.objects.get(pk=pk) template = loader.get_template('management/deleted.html') if ip.uid: path = os.path.join(config_path_work, ip.uid) if os.path.exists(path): rmtree(path) context = { 'uid': ip.uid, } ip.uid = "" ...
107
107
359
9
98
eark-project/access_dipcreator
management/views.py
Python
checkout
checkout
107
143
107
108
85e47b7c3db2452512d830e876a6c0081712dbbe
bigcode/the-stack
train
bcef4bd4e3ec1a658237146f
train
function
@login_required def delete(request, pk): ip = InformationPackage.objects.get(pk=pk) template = loader.get_template('management/deleted.html') if ip.uid: path = os.path.join(config_path_work, ip.uid) if os.path.exists(path): rmtree(path) context = { 'uid': ip.uid, ...
@login_required def delete(request, pk):
ip = InformationPackage.objects.get(pk=pk) template = loader.get_template('management/deleted.html') if ip.uid: path = os.path.join(config_path_work, ip.uid) if os.path.exists(path): rmtree(path) context = { 'uid': ip.uid, } ip.uid = "" ip.work_dir = "" ...
_file, upload_path, os.path.join(ip_work_dir, 'metadata/sip_creation.log')) print("Package extraction task '%s' to extract package '%s' to working directory: %s" % ( async_res.id, f.name, upload_path)) @login_required def delete(request, pk):
64
64
102
9
55
eark-project/access_dipcreator
management/views.py
Python
delete
delete
90
104
90
91
fa09a94eb8a6a470a2a2cff4e4b66773902c9f41
bigcode/the-stack
train
9cd56c3d570a2314f605ca83
train
function
@login_required @csrf_exempt def ip_detail_table(request): logger.info("Updating ip table ...") pkg_id = request.POST['pkg_id'] ip = InformationPackage.objects.get(pk=pkg_id) logger.info("- version: %s" % ip.version) context = { "ip": ip, "config_path_work": config_path_work } ...
@login_required @csrf_exempt def ip_detail_table(request):
logger.info("Updating ip table ...") pkg_id = request.POST['pkg_id'] ip = InformationPackage.objects.get(pk=pkg_id) logger.info("- version: %s" % ip.version) context = { "ip": ip, "config_path_work": config_path_work } return render(request, 'management/iptable.html', context...
(__name__) from django.utils.translation import ugettext_lazy as _ @login_required def index(request): template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request)) @login_required @csrf_exempt def ip_detail_table(request)...
64
64
94
14
50
eark-project/access_dipcreator
management/views.py
Python
ip_detail_table
ip_detail_table
42
53
42
44
1ca24af2ae8d6df6589ebbd208156ab2bbe621cf
bigcode/the-stack
train
ec433a04575dbb92279ea03d
train
function
def upload_file(upload_path, f): print("Upload file '%s' to working directory: %s" % (f.name, upload_path)) if not os.path.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: ...
def upload_file(upload_path, f):
print("Upload file '%s' to working directory: %s" % (f.name, upload_path)) if not os.path.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: for chunk in f.chunks(): ...
render(request, '%s/overview.html' % area, {'informationpackage': table}) @login_required def render_network(request): template = loader.get_template('management/render_network.html') context = { } return HttpResponse(template.render(context=context, request=request)) def upload_file(upload_path, f)...
64
64
92
8
56
eark-project/access_dipcreator
management/views.py
Python
upload_file
upload_file
233
241
233
233
c37505f44e5ac91d7831eced0f4909d97a5a7edf
bigcode/the-stack
train
1a53904d855eff798c5fed84
train
function
@login_required def render_network(request): template = loader.get_template('management/render_network.html') context = { } return HttpResponse(template.render(context=context, request=request))
@login_required def render_network(request):
template = loader.get_template('management/render_network.html') context = { } return HttpResponse(template.render(context=context, request=request))
'informationpackage': table, } if request.method == "POST": return render(request, 'earkweb/ipstable.html', context=context) else: return render(request, '%s/overview.html' % area, {'informationpackage': table}) @login_required def render_network(request):
64
64
38
8
56
eark-project/access_dipcreator
management/views.py
Python
render_network
render_network
224
230
224
225
2c8184bfc964263f4b875dc4563624c196818c19
bigcode/the-stack
train
6f1e45c8967d1482a627c3cd
train
function
@login_required @csrf_exempt def informationpackages_overview(request): area = "management" areacode = "2" filterword = request.POST['filterword'] if 'filterword' in request.POST.keys() else "" sql_query = """ select ip.id as id, ip.work_dir as path, ip.uid as uid, ip.package_name as package_name, ...
@login_required @csrf_exempt def informationpackages_overview(request):
area = "management" areacode = "2" filterword = request.POST['filterword'] if 'filterword' in request.POST.keys() else "" sql_query = """ select ip.id as id, ip.work_dir as path, ip.uid as uid, ip.package_name as package_name, CONCAT('<a href="/earkweb/management/modify/',ip.id,'/" data-toggle="...
glyphicon glyphicon-ok-sign" aria-hidden="true" style="color:green"/>' ) elif value == "Error": return mark_safe( 'Error <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true" style="color:#91170A"/>' ) elif value == "Warning": ...
124
124
414
15
108
eark-project/access_dipcreator
management/views.py
Python
informationpackages_overview
informationpackages_overview
196
221
196
198
6cdd883c4fef77e3f78f29b0fa3c366ab9eaed08
bigcode/the-stack
train
37e192f77169bac16e602fcc
train
class
class InformationPackageTable(tables.Table): from django_tables2.utils import A area = "management" identifier = tables.LinkColumn('%s:storage_area' % area, kwargs={'section': area, 'identifier': A('identifier')}, verbose_name=_("Archived Information Package"), ...
class InformationPackageTable(tables.Table):
from django_tables2.utils import A area = "management" identifier = tables.LinkColumn('%s:storage_area' % area, kwargs={'section': area, 'identifier': A('identifier')}, verbose_name=_("Archived Information Package"), attrs={'a': {'data-t...
= "%s: %s" % (err_msg, json_err["message"]) except JSONDecodeError: pass return render(request, 'earkweb/error.html', { 'header': 'Checkout error', 'message': err_msg }) resp_json = json.loads(response.text) context = { 'msg_checkout_confirm': resp_json['...
139
139
464
8
131
eark-project/access_dipcreator
management/views.py
Python
InformationPackageTable
InformationPackageTable
146
193
146
146
31681b3fd09753ba0326ace1af55c49c92120ceb
bigcode/the-stack
train
98237e74609e00ef4efe2607
train
function
@login_required def index(request): template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request))
@login_required def index(request):
template = loader.get_template('management/index.html') context = { } return HttpResponse(template.render(context=context, request=request))
Package.objects.get(pk=pkg_id) logger.info("- version: %s" % ip.version) context = { "ip": ip, "config_path_work": config_path_work } return render(request, 'management/iptable.html', context=context) @login_required def index(request):
64
64
36
7
57
eark-project/access_dipcreator
management/views.py
Python
index
index
56
62
56
57
77ccb3b07a315e2f2ba3355bded52bf167c0561a
bigcode/the-stack
train
4cda72a7346386dee7e1d679
train
class
class TestSetQCS: """ Weighted mean iou computation for the query complexity tier of TSS Attributes ----------- fold_mious : [ [float] ] mean intersection over union values for each fold, for each partition Methods ------- update( fold_number, p...
class TestSetQCS:
""" Weighted mean iou computation for the query complexity tier of TSS Attributes ----------- fold_mious : [ [float] ] mean intersection over union values for each fold, for each partition Methods ------- update( fold_number, part_type, mean_iou...
on-salient, hard-salient and hard-non-salient) using the update function. The final LCA and HCA can be obtained at a single fold-level using the fold_lca() and fold_hca() functions. Average LCA and HCA across the folds can be obtained using the mean_lca() and mean_hca() functions. Example: -------- ``` tsq = Tes...
256
256
931
6
249
fewshotseg/toss
src/filescores2ics.py
Python
TestSetQCS
TestSetQCS
27
149
27
27
b66ae74af8c6d119c5d3b32a0b12c28b7b7a3418
bigcode/the-stack
train
6f65b3fb8e204fa0d7997c09
train
function
def point_cloud_2_top(points, res=0.1, zres=0.3, side_range=(-10., 10.), # left-most to right-most fwd_range=(-10., 10.), # back-most to forward-most height_range=(-2., 2.), # bottom-most to upper-most ...
def point_cloud_2_top(points, res=0.1, zres=0.3, side_range=(-10., 10.), # left-most to right-most fwd_range=(-10., 10.), # back-most to forward-most height_range=(-2., 2.), # bottom-most to upper-most ...
""" Creates an birds eye view representation of the point cloud data for MV3D. Args: points: (numpy array) N rows of points data Each point should be specified by at least 3 elements x,y,z res: (float) Desired resolution in ...
import numpy as np import os import matplotlib.pyplot as plt # ============================================================================== # POINT_CLOUD_2_BIRDSEYE # ============================================================================== def point_clo...
109
256
1,179
77
32
klockeph/MV3D_TF
tools/read_lidar.py
Python
point_cloud_2_top
point_cloud_2_top
10
115
10
16
a1eb71eedf39e953d181d9062a239bb3e4bb05b5
bigcode/the-stack
train
7bf7279cc00ec1765613b26b
train
function
def get_ast(query: str): return parse(Source(query))
def get_ast(query: str):
return parse(Source(query))
=validation_errors, invalid=True) return execute(self.schema, ast) @classmethod def format_error(cls, error: Exception) -> dict: if isinstance(error, GraphQLSyntaxError): return format_error(error) return {'message': str(error)} def get_ast(query: str):
63
64
13
7
56
karol-gruszczyk/sloth-gql
slothql/query.py
Python
get_ast
get_ast
39
40
39
39
7833f488753a3058a99a8e180842ee1dafd5f64a
bigcode/the-stack
train
c6e015f8b53f4faa15e65143
train
class
class QueryExecutor: def __init__(self, schema: GraphQLSchema) -> None: self.schema = schema assert isinstance(schema, GraphQLSchema), f'schema has to be of type GraphQLSchema, not {self.schema}' def query(self, query: str) -> dict: assert isinstance(query, str), f'Expected query string...
class QueryExecutor:
def __init__(self, schema: GraphQLSchema) -> None: self.schema = schema assert isinstance(schema, GraphQLSchema), f'schema has to be of type GraphQLSchema, not {self.schema}' def query(self, query: str) -> dict: assert isinstance(query, str), f'Expected query string, got {query}' ...
from graphql import Source, parse, validate, GraphQLSchema from graphql.error import format_error, GraphQLSyntaxError from graphql.execution import execute, ExecutionResult import slothql class QueryExecutor:
43
72
241
4
38
karol-gruszczyk/sloth-gql
slothql/query.py
Python
QueryExecutor
QueryExecutor
8
36
8
8
3e675341b6c6e762582cb5f6f39f0f32d5cc1105
bigcode/the-stack
train
d85fa77db75d811af092e001
train
function
def gql(schema: slothql.Schema, query: str) -> dict: return QueryExecutor(schema).query(query)
def gql(schema: slothql.Schema, query: str) -> dict:
return QueryExecutor(schema).query(query)
_error(cls, error: Exception) -> dict: if isinstance(error, GraphQLSyntaxError): return format_error(error) return {'message': str(error)} def get_ast(query: str): return parse(Source(query)) def gql(schema: slothql.Schema, query: str) -> dict:
64
64
25
16
48
karol-gruszczyk/sloth-gql
slothql/query.py
Python
gql
gql
43
44
43
43
a30277a61ee1661674ab7eb21b935ec2097e0647
bigcode/the-stack
train
23c77945ccc7713f15fc7ab6
train
function
def update_cache(val): Cache.storage.clear() Cache.storage = val regenerate_file()
def update_cache(val):
Cache.storage.clear() Cache.storage = val regenerate_file()
) @app.route("/api/cache/update") def force_update(): val = requests.get(api_address + "/e/diseases").json() update_cache(val) print(Cache.storage) return "Success" @app.route("/api/cache") def get_cache(): return jsonify(Cache.storage) def update_cache(val):
64
64
20
5
59
TriedAngle/diseaster
services/matcher.py
Python
update_cache
update_cache
84
87
84
84
1f0952feeaeda88ca855b9043a62c6af424b5a8d
bigcode/the-stack
train
6b7c1387468422e2052dcfbd
train
class
class Cache: storage = {}
class Cache:
storage = {}
import requests import json import jsonlines load_dotenv() key = os.environ.get("OPENAI_KEY") address = os.environ.get("MATCH_SERVICE_ADDRESS") api_address = os.environ.get("BACKEND_REACH_ADDRESS") openai.api_key = key app = Flask(__name__) class Cache:
64
64
7
3
61
TriedAngle/diseaster
services/matcher.py
Python
Cache
Cache
19
20
19
19
df20f87f3b97ce2545a9c85bd78807bc5e906b92
bigcode/the-stack
train
02443943322693e10da80966
train
function
@app.route("/api/cache") def get_cache(): return jsonify(Cache.storage)
@app.route("/api/cache") def get_cache():
return jsonify(Cache.storage)
_name + " first" } return jsonify(response) @app.route("/api/cache/update") def force_update(): val = requests.get(api_address + "/e/diseases").json() update_cache(val) print(Cache.storage) return "Success" @app.route("/api/cache") def get_cache():
64
64
16
10
54
TriedAngle/diseaster
services/matcher.py
Python
get_cache
get_cache
79
81
79
80
fbbc77bdf80fb5d2bcea43203d766df4a8e55683
bigcode/the-stack
train
5e849c8e73fa134253e0b259
train
function
def extract(text) -> List[str]: response = openai.Completion.create( engine="davinci", prompt="Read this patient phone call:\n\"\"\"\n {} \n\"\"\"\nAnswer the following questions:\n\n1. What is the patients name?\n2. What symptoms is he mentioning?\n3. Return the symptoms as a Python list object\n4....
def extract(text) -> List[str]:
response = openai.Completion.create( engine="davinci", prompt="Read this patient phone call:\n\"\"\"\n {} \n\"\"\"\nAnswer the following questions:\n\n1. What is the patients name?\n2. What symptoms is he mentioning?\n3. Return the symptoms as a Python list object\n4. What disease could he have?\n5....
"/e/diseases").json() update_cache(val) print(Cache.storage) return "Success" @app.route("/api/cache") def get_cache(): return jsonify(Cache.storage) def update_cache(val): Cache.storage.clear() Cache.storage = val regenerate_file() def extract(text) -> List[str]:
67
67
224
8
59
TriedAngle/diseaster
services/matcher.py
Python
extract
extract
90
109
90
90
93de5a6507a0fff681429dd769d2fc1113bc78ff
bigcode/the-stack
train
5fd97b0a6ef504971fdf0d80
train
function
@app.route("/") def index(): return "hello world!"
@app.route("/") def index():
return "hello world!"
load_dotenv() key = os.environ.get("OPENAI_KEY") address = os.environ.get("MATCH_SERVICE_ADDRESS") api_address = os.environ.get("BACKEND_REACH_ADDRESS") openai.api_key = key app = Flask(__name__) class Cache: storage = {} @app.route("/") def index():
63
64
12
6
57
TriedAngle/diseaster
services/matcher.py
Python
index
index
23
25
23
24
80eda248a84c960697e9b31149ebe513b4aeda7c
bigcode/the-stack
train
49c2704e676f3fb47675ec86
train
function
@app.route("/api/cache/update") def force_update(): val = requests.get(api_address + "/e/diseases").json() update_cache(val) print(Cache.storage) return "Success"
@app.route("/api/cache/update") def force_update():
val = requests.get(api_address + "/e/diseases").json() update_cache(val) print(Cache.storage) return "Success"
dep['name'] print(dep_name) response = { "text": "you are likely to have: " + max_val + "\nwe recommend going to the Department of " + dep_name + " first" } return jsonify(response) @app.route("/api/cache/update") def force_update():
64
64
42
11
53
TriedAngle/diseaster
services/matcher.py
Python
force_update
force_update
71
76
71
72
fc422c0d9815f38edefa41bc5c032bee800a92d0
bigcode/the-stack
train
efecdeebb3cd6e30e5a8428c
train
function
def regenerate_file(): temp = [] for val in Cache.storage: symptoms = "" metadata = val["name"] for symptom in val["symptoms"]: symptoms += symptom["name"] + ", " size = len(symptoms) mod_string = symptoms[:size - 2] symptoms = mod_string te...
def regenerate_file():
temp = [] for val in Cache.storage: symptoms = "" metadata = val["name"] for symptom in val["symptoms"]: symptoms += symptom["name"] + ", " size = len(symptoms) mod_string = symptoms[:size - 2] symptoms = mod_string temp.append({'text': symp...
=0, stop=["7."] ) text_output = response["choices"][0]["text"] b = "234567." for char in b: text_output = text_output.replace(char, "") result = text_output.splitlines() return result[2] def regenerate_file():
64
64
116
4
60
TriedAngle/diseaster
services/matcher.py
Python
regenerate_file
regenerate_file
112
130
112
112
ee81c03ea397f36d6392a3ebc8b167f20788d987
bigcode/the-stack
train
05ad05bef5e0e7af6f92a509
train
function
@app.route("/api/matcher", methods=['GET', 'POST']) def get_matching(): content = request.form text = content['text'] print(text) query_as_list = extract(text) query = str(query_as_list).replace("[", "").replace("]", "").replace("'", "") result = openai.Engine("davinci").search( file="...
@app.route("/api/matcher", methods=['GET', 'POST']) def get_matching():
content = request.form text = content['text'] print(text) query_as_list = extract(text) query = str(query_as_list).replace("[", "").replace("]", "").replace("'", "") result = openai.Engine("davinci").search( file="file-cEbtzr5OPbMfgHXroCUm5hT4", query=query, return_meta...
lines load_dotenv() key = os.environ.get("OPENAI_KEY") address = os.environ.get("MATCH_SERVICE_ADDRESS") api_address = os.environ.get("BACKEND_REACH_ADDRESS") openai.api_key = key app = Flask(__name__) class Cache: storage = {} @app.route("/") def index(): return "hello world!" @app.route("/api/matcher", m...
90
91
305
18
72
TriedAngle/diseaster
services/matcher.py
Python
get_matching
get_matching
28
68
28
29
7325552cbafdfb6070af868427601d372c2533ed
bigcode/the-stack
train
faea31882b37ca2aef00d50c
train
function
def merge_last(x, n_dims): """ merge the last n_dims to a dimension """ s = x.size() assert n_dims > 1 and n_dims < len(s) return x.view(*s[:-n_dims], -1)
def merge_last(x, n_dims):
""" merge the last n_dims to a dimension """ s = x.size() assert n_dims > 1 and n_dims < len(s) return x.view(*s[:-n_dims], -1)
list(shape) assert shape.count(-1) <= 1 if -1 in shape: shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape)) return x.view(*x.size()[:-1], *shape) def merge_last(x, n_dims):
64
64
55
8
56
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
merge_last
merge_last
42
48
42
42
c5987a82e98a5853396c5adba9a2daebfbf72345
bigcode/the-stack
train