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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b79a9d1b8656ca8b2ca1b4f | train | class | class EmailNotificationSchema(NotificationSchema):
to = fields.Str(required=True)
template = fields.Str(required=True)
@validates('to')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
raise ValidationError(str(e))
| class EmailNotificationSchema(NotificationSchema):
| to = fields.Str(required=True)
template = fields.Str(required=True)
@validates('to')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
raise ValidationError(str(e))
| except InvalidPhoneError as error:
raise ValidationError('Invalid phone number: {}'.format(error))
@post_load
def format_phone_number(self, item):
item['to'] = validate_and_format_phone_number(item['to'], international=True)
return item
class EmailNotificationSchema(Notifica... | 64 | 64 | 62 | 7 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | EmailNotificationSchema | EmailNotificationSchema | 512 | 521 | 512 | 512 | 97aff9760f8f264b650d21f1a9158999eca8b887 | bigcode/the-stack | train |
9d18b1eda87b0a54389c559f | train | class | class EventSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.Event
strict = True
| class EventSchema(BaseSchema):
| class Meta(BaseSchema.Meta):
model = models.Event
strict = True
| ApiKeyHistorySchema(ma.Schema):
id = fields.UUID()
name = fields.String()
service_id = fields.UUID()
expiry_date = fields.DateTime()
created_at = fields.DateTime()
updated_at = fields.DateTime()
created_by_id = fields.UUID()
class EventSchema(BaseSchema):
| 64 | 64 | 24 | 6 | 58 | TechforgoodCAST/notifications-api | app/schemas.py | Python | EventSchema | EventSchema | 725 | 728 | 725 | 725 | 7b05a65eac1b39075c39569bad18adda719e4cdf | bigcode/the-stack | train |
ce37bb91be63cbe3f058fd60 | train | class | class ApiKeyHistorySchema(ma.Schema):
id = fields.UUID()
name = fields.String()
service_id = fields.UUID()
expiry_date = fields.DateTime()
created_at = fields.DateTime()
updated_at = fields.DateTime()
created_by_id = fields.UUID()
| class ApiKeyHistorySchema(ma.Schema):
| id = fields.UUID()
name = fields.String()
service_id = fields.UUID()
expiry_date = fields.DateTime()
created_at = fields.DateTime()
updated_at = fields.DateTime()
created_by_id = fields.UUID()
| created_at = fields.DateTime()
updated_at = fields.DateTime()
active = fields.Boolean()
message_limit = fields.Integer()
restricted = fields.Boolean()
email_from = fields.String()
created_by_id = fields.UUID()
version = fields.Integer()
class ApiKeyHistorySchema(ma.Schema):
| 64 | 64 | 59 | 8 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ApiKeyHistorySchema | ApiKeyHistorySchema | 715 | 722 | 715 | 715 | baa5024d9031d8dc488c693b5c387714665adf16 | bigcode/the-stack | train |
750f3da9130616086e0327a7 | train | class | class TemplateSchema(BaseTemplateSchema, UUIDsAsStringsMixin):
created_by = field_for(models.Template, 'created_by', required=True)
process_type = field_for(models.Template, 'process_type')
redact_personalisation = fields.Method("redact")
def redact(self, template):
return template.redact_pers... | class TemplateSchema(BaseTemplateSchema, UUIDsAsStringsMixin):
| created_by = field_for(models.Template, 'created_by', required=True)
process_type = field_for(models.Template, 'process_type')
redact_personalisation = fields.Method("redact")
def redact(self, template):
return template.redact_personalisation
@validates_schema
def validate_type(self, d... | _text(self, template):
return template.get_reply_to_text()
class Meta(BaseSchema.Meta):
model = models.Template
exclude = ("service_id", "jobs", "service_letter_contact_id", "broadcast_messages")
strict = True
class TemplateSchema(BaseTemplateSchema, UUIDsAsStringsMixin):
| 64 | 64 | 135 | 13 | 50 | TechforgoodCAST/notifications-api | app/schemas.py | Python | TemplateSchema | TemplateSchema | 375 | 389 | 375 | 376 | f5f248f8b28a5bea4fea0001fe77bc34beabe27b | bigcode/the-stack | train |
ba53f7119fcb83de54392d17 | train | class | class ProviderDetailsHistorySchema(BaseSchema):
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
class Meta(BaseSchema.Meta):
model = models.ProviderDetailsHistory
exclude = ("provider_rates", "provider_stats")
strict = True
| class ProviderDetailsHistorySchema(BaseSchema):
| created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
class Meta(BaseSchema.Meta):
model = models.ProviderDetailsHistory
exclude = ("provider_rates", "provider_stats")
strict = True
| ):
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
class Meta(BaseSchema.Meta):
model = models.ProviderDetails
exclude = ("provider_rates", "provider_stats")
strict = True
class ProviderDetailsHistorySchema(BaseSchema):
| 64 | 64 | 64 | 8 | 55 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ProviderDetailsHistorySchema | ProviderDetailsHistorySchema | 219 | 225 | 219 | 219 | 82fa19b78edfdcaa95f3bd4675b7a875ebf52739 | bigcode/the-stack | train |
06caafe8f1a126f38fb288aa | train | class | class TemplateSchemaNoDetail(TemplateSchema):
class Meta(TemplateSchema.Meta):
exclude = TemplateSchema.Meta.exclude + (
'archived',
'broadcast_data',
'created_at',
'created_by',
'created_by_id',
'hidden',
'postage',
... | class TemplateSchemaNoDetail(TemplateSchema):
| class Meta(TemplateSchema.Meta):
exclude = TemplateSchema.Meta.exclude + (
'archived',
'broadcast_data',
'created_at',
'created_by',
'created_by_id',
'hidden',
'postage',
'process_type',
'redact_perso... | (self, data):
if data.get('template_type') in {models.EMAIL_TYPE, models.LETTER_TYPE}:
subject = data.get('subject')
if not subject or subject.strip() == '':
raise ValidationError('Invalid template subject', 'subject')
class TemplateSchemaNoDetail(TemplateSchema):
| 64 | 64 | 152 | 9 | 55 | TechforgoodCAST/notifications-api | app/schemas.py | Python | TemplateSchemaNoDetail | TemplateSchemaNoDetail | 392 | 417 | 392 | 392 | 47eb1189bb4876f5805a283089db83ec140569d1 | bigcode/the-stack | train |
046f0ddac3fab13e98e8dc14 | train | class | class BaseTemplateSchema(BaseSchema):
reply_to = fields.Method("get_reply_to", allow_none=True)
reply_to_text = fields.Method("get_reply_to_text", allow_none=True)
def get_reply_to(self, template):
return template.reply_to
def get_reply_to_text(self, template):
return template.get_repl... | class BaseTemplateSchema(BaseSchema):
| reply_to = fields.Method("get_reply_to", allow_none=True)
reply_to_text = fields.Method("get_reply_to_text", allow_none=True)
def get_reply_to(self, template):
return template.reply_to
def get_reply_to_text(self, template):
return template.get_reply_to_text()
class Meta(BaseSchema... | )
class NotificationModelSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.Notification
strict = True
exclude = ('_personalisation', 'job', 'service', 'template', 'api_key',)
status = fields.String(required=False)
class BaseTemplateSchema(BaseSchema):
| 64 | 64 | 110 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | BaseTemplateSchema | BaseTemplateSchema | 359 | 372 | 359 | 359 | 79e8b6af870b00efa1b1ffd0a5488b9d4ef1f919 | bigcode/the-stack | train |
cf60e7a16fd2cb58fd9b573c | train | class | class ServiceHistorySchema(ma.Schema):
id = fields.UUID()
name = fields.String()
description = fields.String()
created_at = fields.DateTime()
updated_at = fields.DateTime()
active = fields.Boolean()
message_limit = fields.Integer()
restricted = fields.Boolean()
email_from = fields.St... | class ServiceHistorySchema(ma.Schema):
| id = fields.UUID()
name = fields.String()
description = fields.String()
created_at = fields.DateTime()
updated_at = fields.DateTime()
active = fields.Boolean()
message_limit = fields.Integer()
restricted = fields.Boolean()
email_from = fields.String()
created_by_id = fields.UUID(... | in in_data['status']]
return in_data
@validates('page')
def validate_page(self, value):
_validate_positive_number(value)
@validates('page_size')
def validate_page_size(self, value):
_validate_positive_number(value)
class ServiceHistorySchema(ma.Schema):
| 64 | 64 | 81 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ServiceHistorySchema | ServiceHistorySchema | 701 | 712 | 701 | 701 | 289908b5b6420da1aaae1217eca41d61973c3f54 | bigcode/the-stack | train |
950be26210c4c51fa046ceca | train | class | class NotificationWithPersonalisationSchema(NotificationWithTemplateSchema):
template_history = fields.Nested(TemplateHistorySchema, attribute="template",
only=['id', 'name', 'template_type', 'content', 'subject', 'version'],
dump_only=True)
... | class NotificationWithPersonalisationSchema(NotificationWithTemplateSchema):
| template_history = fields.Nested(TemplateHistorySchema, attribute="template",
only=['id', 'name', 'template_type', 'content', 'subject', 'version'],
dump_only=True)
class Meta(NotificationWithTemplateSchema.Meta):
# mark as many ... | (UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
status = fields.String(required=False)
personalisation = fields.Dict(required=False)
key_type = field_for(models.Notification, 'key_type', required=True)
key_name = fields.String()
@pre_dump
def add_api_key_name(self, in_data):
... | 120 | 120 | 403 | 11 | 108 | TechforgoodCAST/notifications-api | app/schemas.py | Python | NotificationWithPersonalisationSchema | NotificationWithPersonalisationSchema | 565 | 616 | 565 | 565 | 7b070e8490b35ba6d62844f17b59c6f5e59d375a | bigcode/the-stack | train |
c187c6f6f15b50ab812eb7b3 | train | class | class NotificationsFilterSchema(ma.Schema):
class Meta:
strict = True
template_type = fields.Nested(BaseTemplateSchema, only=['template_type'], many=True)
status = fields.Nested(NotificationModelSchema, only=['status'], many=True)
page = fields.Int(required=False)
page_size = fields.Int(re... | class NotificationsFilterSchema(ma.Schema):
| class Meta:
strict = True
template_type = fields.Nested(BaseTemplateSchema, only=['template_type'], many=True)
status = fields.Nested(NotificationModelSchema, only=['status'], many=True)
page = fields.Int(required=False)
page_size = fields.Int(required=False)
limit_days = fields.Int(req... | except InvalidEmailError as e:
raise ValidationError(str(e))
class EmailDataSchema(ma.Schema):
class Meta:
strict = True
email = fields.Str(required=True)
def __init__(self, partial_email=False):
super().__init__()
self.partial_email = partial_email
@validates(... | 117 | 117 | 391 | 7 | 110 | TechforgoodCAST/notifications-api | app/schemas.py | Python | NotificationsFilterSchema | NotificationsFilterSchema | 655 | 698 | 655 | 656 | f01b62628374a783cce2ce37bd01f490f3a595ca | bigcode/the-stack | train |
d3f0155696ea26936f4a0bfb | train | class | class ApiKeySchema(BaseSchema):
created_by = field_for(models.ApiKey, 'created_by', required=True)
key_type = field_for(models.ApiKey, 'key_type', required=True)
class Meta(BaseSchema.Meta):
model = models.ApiKey
exclude = ("service", "_secret")
strict = True
| class ApiKeySchema(BaseSchema):
| created_by = field_for(models.ApiKey, 'created_by', required=True)
key_type = field_for(models.ApiKey, 'key_type', required=True)
class Meta(BaseSchema.Meta):
model = models.ApiKey
exclude = ("service", "_secret")
strict = True
| ', format=DATETIME_FORMAT_NO_TIMEZONE)
def get_reply_to(self, template):
return template.reply_to
def get_reply_to_text(self, template):
return template.get_reply_to_text()
class Meta(BaseSchema.Meta):
model = models.TemplateHistory
class ApiKeySchema(BaseSchema):
| 64 | 64 | 69 | 7 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ApiKeySchema | ApiKeySchema | 439 | 447 | 439 | 440 | de4af8e717330b980eec5870c407ba485ff1c1fb | bigcode/the-stack | train |
3ea633b6540ace997bd80277 | train | class | class NotificationSchema(ma.Schema):
class Meta:
strict = True
status = fields.String(required=False)
personalisation = fields.Dict(required=False)
| class NotificationSchema(ma.Schema):
| class Meta:
strict = True
status = fields.String(required=False)
personalisation = fields.Dict(required=False)
| _validate_datetime_not_more_than_96_hours_in_future(value)
class Meta(BaseSchema.Meta):
model = models.Job
exclude = (
'notifications',
'notifications_delivered',
'notifications_failed',
'notifications_sent',
)
strict = True
cl... | 64 | 64 | 32 | 6 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | NotificationSchema | NotificationSchema | 487 | 493 | 487 | 488 | 2401a26ebe48ef96315f8ec78746152be929870c | bigcode/the-stack | train |
3a1321bf202c3e42ed05a97a | train | class | class JobSchema(BaseSchema):
created_by_user = fields.Nested(UserSchema, attribute="created_by",
dump_to="created_by", only=["id", "name"], dump_only=True)
created_by = field_for(models.Job, 'created_by', required=True, load_only=True)
job_status = field_for(models.JobSt... | class JobSchema(BaseSchema):
| created_by_user = fields.Nested(UserSchema, attribute="created_by",
dump_to="created_by", only=["id", "name"], dump_only=True)
created_by = field_for(models.Job, 'created_by', required=True, load_only=True)
job_status = field_for(models.JobStatus, 'name', required=False)... | model = models.TemplateHistory
class ApiKeySchema(BaseSchema):
created_by = field_for(models.ApiKey, 'created_by', required=True)
key_type = field_for(models.ApiKey, 'key_type', required=True)
class Meta(BaseSchema.Meta):
model = models.ApiKey
exclude = ("service", "_secret")
... | 82 | 82 | 276 | 6 | 75 | TechforgoodCAST/notifications-api | app/schemas.py | Python | JobSchema | JobSchema | 450 | 484 | 450 | 450 | 3b02809c189ff7ab628d4527243925a2cffafa1d | bigcode/the-stack | train |
e30b945393362e72a080be3a | train | class | class InvitedUserSchema(BaseSchema):
auth_type = field_for(models.InvitedUser, 'auth_type')
class Meta(BaseSchema.Meta):
model = models.InvitedUser
strict = True
@validates('email_address')
def validate_to(self, value):
try:
validate_email_address(value)
exc... | class InvitedUserSchema(BaseSchema):
| auth_type = field_for(models.InvitedUser, 'auth_type')
class Meta(BaseSchema.Meta):
model = models.InvitedUser
strict = True
@validates('email_address')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
... |
else:
in_data['content_char_count'] = template.content_count
in_data.pop('personalisation', None)
in_data['template'].pop('content', None)
in_data['template'].pop('subject', None)
return in_data
class InvitedUserSchema(BaseSchema):
| 64 | 64 | 83 | 8 | 55 | TechforgoodCAST/notifications-api | app/schemas.py | Python | InvitedUserSchema | InvitedUserSchema | 619 | 631 | 619 | 619 | ee4f16308a8475cba55672793e6af956b401b371 | bigcode/the-stack | train |
4c8adbee6f1722dc5eb1b563 | train | class | class ProviderDetailsSchema(BaseSchema):
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
class Meta(BaseSchema.Meta):
model = models.ProviderDetails
exclude = ("provider_rates", "provider_stats")
strict = True
| class ProviderDetailsSchema(BaseSchema):
| created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
class Meta(BaseSchema.Meta):
model = models.ProviderDetails
exclude = ("provider_rates", "provider_stats")
strict = True
| = ('password')
strict = True
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in self.fields:
raise ValidationError('Unknown field name {}'.format(key))
class ProviderDetailsSchema(BaseSc... | 64 | 64 | 62 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ProviderDetailsSchema | ProviderDetailsSchema | 210 | 216 | 210 | 210 | ec7ced7e4d3b2d5097ee837e7cbbf1a4a4ea8995 | bigcode/the-stack | train |
f304ffe50bfec44ac68cc42f | train | class | class UserUpdatePasswordSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.User
only = ('password')
strict = True
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in self... | class UserUpdatePasswordSchema(BaseSchema):
| class Meta(BaseSchema.Meta):
model = models.User
only = ('password')
strict = True
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in self.fields:
raise ValidationErro... | Invalid phone number: {}'.format(error))
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in self.fields:
raise ValidationError('Unknown field name {}'.format(key))
class UserUpdatePasswordSchema(... | 64 | 64 | 80 | 8 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | UserUpdatePasswordSchema | UserUpdatePasswordSchema | 196 | 207 | 196 | 197 | ae59c61f482def4e7e797701dc24772f74cae9ce | bigcode/the-stack | train |
81e5dae695fbc3ef89c6bf6d | train | class | class UserUpdateAttributeSchema(BaseSchema):
auth_type = field_for(models.User, 'auth_type')
class Meta(BaseSchema.Meta):
model = models.User
exclude = (
'_password',
'created_at',
'failed_login_count',
'id',
'logged_in_at',
... | class UserUpdateAttributeSchema(BaseSchema):
| auth_type = field_for(models.User, 'auth_type')
class Meta(BaseSchema.Meta):
model = models.User
exclude = (
'_password',
'created_at',
'failed_login_count',
'id',
'logged_in_at',
'password_changed_at',
'platfor... | (value)
except InvalidEmailError as e:
raise ValidationError(str(e))
@validates('mobile_number')
def validate_mobile_number(self, value):
try:
if value is not None:
validate_phone_number(value, international=True)
except InvalidPhoneError as error... | 82 | 82 | 275 | 8 | 74 | TechforgoodCAST/notifications-api | app/schemas.py | Python | UserUpdateAttributeSchema | UserUpdateAttributeSchema | 149 | 193 | 149 | 149 | 09540a1072fd2ac273f94cc0997842704966f162 | bigcode/the-stack | train |
6b66843348bb99d34c7048fc | train | class | class UUIDsAsStringsMixin:
@post_dump()
def __post_dump(self, data):
for key, value in data.items():
if isinstance(value, UUID):
data[key] = str(value)
if isinstance(value, list):
data[key] = [
(str(item) if isinstance(item, U... | class UUIDsAsStringsMixin:
@post_dump()
| def __post_dump(self, data):
for key, value in data.items():
if isinstance(value, UUID):
data[key] = str(value)
if isinstance(value, list):
data[key] = [
(str(item) if isinstance(item, UUID) else item)
for item... | in the future"):
if dte > datetime.utcnow():
raise ValidationError(msg)
def _validate_datetime_not_in_past(dte, msg="Date cannot be in the past"):
if dte < datetime.utcnow():
raise ValidationError(msg)
class UUIDsAsStringsMixin:
@post_dump()
| 64 | 64 | 80 | 12 | 52 | TechforgoodCAST/notifications-api | app/schemas.py | Python | UUIDsAsStringsMixin | UUIDsAsStringsMixin | 62 | 74 | 62 | 63 | 4cdfaff4e2f1b542109f5340e397e37ab1b76331 | bigcode/the-stack | train |
3c32a482c0ed9696c1a59c4a | train | function | def _validate_datetime_not_in_future(dte, msg="Date cannot be in the future"):
if dte > datetime.utcnow():
raise ValidationError(msg)
| def _validate_datetime_not_in_future(dte, msg="Date cannot be in the future"):
| if dte > datetime.utcnow():
raise ValidationError(msg)
| + timedelta(hours=96):
raise ValidationError(msg)
def _validate_not_in_past(dte, msg="Date cannot be in the past"):
if dte < date.today():
raise ValidationError(msg)
def _validate_datetime_not_in_future(dte, msg="Date cannot be in the future"):
| 64 | 64 | 33 | 19 | 45 | TechforgoodCAST/notifications-api | app/schemas.py | Python | _validate_datetime_not_in_future | _validate_datetime_not_in_future | 52 | 54 | 52 | 52 | 22b1f43cbff5655e1dbdd8baf5bf6def2455ef29 | bigcode/the-stack | train |
155dd4324390b588c58b5e50 | train | class | class ServiceSchema(BaseSchema, UUIDsAsStringsMixin):
created_by = field_for(models.Service, 'created_by', required=True)
organisation_type = field_for(models.Service, 'organisation_type')
letter_logo_filename = fields.Method(dump_only=True, serialize='get_letter_logo_filename')
permissions = fields.Me... | class ServiceSchema(BaseSchema, UUIDsAsStringsMixin):
| created_by = field_for(models.Service, 'created_by', required=True)
organisation_type = field_for(models.Service, 'organisation_type')
letter_logo_filename = fields.Method(dump_only=True, serialize='get_letter_logo_filename')
permissions = fields.Method("service_permissions")
email_branding = field_... | def check_unknown_fields(self, data, original_data):
for key in original_data:
if key not in self.fields:
raise ValidationError('Unknown field name {}'.format(key))
class ProviderDetailsSchema(BaseSchema):
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_ad... | 177 | 177 | 591 | 12 | 164 | TechforgoodCAST/notifications-api | app/schemas.py | Python | ServiceSchema | ServiceSchema | 228 | 306 | 228 | 229 | 316dac818715c4e398dff03124514182845132fd | bigcode/the-stack | train |
97d1d5df66a9ecb8d3d4cd7e | train | class | class SmsNotificationSchema(NotificationSchema):
to = fields.Str(required=True)
@validates('to')
def validate_to(self, value):
try:
validate_phone_number(value, international=True)
except InvalidPhoneError as error:
raise ValidationError('Invalid phone number: {}'.fo... | class SmsNotificationSchema(NotificationSchema):
| to = fields.Str(required=True)
@validates('to')
def validate_to(self, value):
try:
validate_phone_number(value, international=True)
except InvalidPhoneError as error:
raise ValidationError('Invalid phone number: {}'.format(error))
@post_load
def format_phone... | notifications',
'notifications_delivered',
'notifications_failed',
'notifications_sent',
)
strict = True
class NotificationSchema(ma.Schema):
class Meta:
strict = True
status = fields.String(required=False)
personalisation = fields.Dict(require... | 64 | 64 | 99 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | SmsNotificationSchema | SmsNotificationSchema | 496 | 509 | 496 | 496 | a8e8f3f573cb77fdea5d550a6f2ff45b74a77abf | bigcode/the-stack | train |
f09b51820a4a63b52c2a9c5a | train | class | class DetailedServiceSchema(BaseSchema):
statistics = fields.Dict()
organisation_type = field_for(models.Service, 'organisation_type')
class Meta(BaseSchema.Meta):
model = models.Service
exclude = (
'all_template_folders',
'annual_billing',
'api_keys',
... | class DetailedServiceSchema(BaseSchema):
| statistics = fields.Dict()
organisation_type = field_for(models.Service, 'organisation_type')
class Meta(BaseSchema.Meta):
model = models.Service
exclude = (
'all_template_folders',
'annual_billing',
'api_keys',
'broadcast_messages',
... | and 'permissions' in in_data:
str_permissions = in_data['permissions']
permissions = []
for p in str_permissions:
permission = ServicePermission(service_id=in_data["id"], permission=p)
permissions.append(permission)
in_data['permissions']... | 64 | 64 | 213 | 7 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | DetailedServiceSchema | DetailedServiceSchema | 309 | 347 | 309 | 309 | a001011d7748c760e81d1d37482977a6a7278f84 | bigcode/the-stack | train |
439fc994685025f2bbd04019 | train | class | class BaseSchema(ma.SQLAlchemyAutoSchema):
class Meta:
load_instance = True
include_relationships = True
def __init__(self, load_json=False, *args, **kwargs):
self.load_json = load_json
super(BaseSchema, self).__init__(*args, **kwargs)
@post_load
def make_instance(self... | class BaseSchema(ma.SQLAlchemyAutoSchema):
| class Meta:
load_instance = True
include_relationships = True
def __init__(self, load_json=False, *args, **kwargs):
self.load_json = load_json
super(BaseSchema, self).__init__(*args, **kwargs)
@post_load
def make_instance(self, data):
"""Deserialize data to an i... | in data.items():
if isinstance(value, UUID):
data[key] = str(value)
if isinstance(value, list):
data[key] = [
(str(item) if isinstance(item, UUID) else item)
for item in value
]
class BaseSchema(ma.SQLAlch... | 63 | 64 | 153 | 9 | 54 | TechforgoodCAST/notifications-api | app/schemas.py | Python | BaseSchema | BaseSchema | 77 | 96 | 77 | 78 | 85b5c5cc9907b536b559b4ad73c45222a97196d1 | bigcode/the-stack | train |
08303d27a1052507b2105250 | train | function | def _validate_datetime_not_in_past(dte, msg="Date cannot be in the past"):
if dte < datetime.utcnow():
raise ValidationError(msg)
| def _validate_datetime_not_in_past(dte, msg="Date cannot be in the past"):
| if dte < datetime.utcnow():
raise ValidationError(msg)
| te < date.today():
raise ValidationError(msg)
def _validate_datetime_not_in_future(dte, msg="Date cannot be in the future"):
if dte > datetime.utcnow():
raise ValidationError(msg)
def _validate_datetime_not_in_past(dte, msg="Date cannot be in the past"):
| 64 | 64 | 34 | 20 | 44 | TechforgoodCAST/notifications-api | app/schemas.py | Python | _validate_datetime_not_in_past | _validate_datetime_not_in_past | 57 | 59 | 57 | 57 | 576482937d80780ea7f6a4e99d3ecceca5aaeb50 | bigcode/the-stack | train |
3fb5d1afa64f285b07930e0c | train | function | def _validate_not_in_past(dte, msg="Date cannot be in the past"):
if dte < date.today():
raise ValidationError(msg)
| def _validate_not_in_past(dte, msg="Date cannot be in the past"):
| if dte < date.today():
raise ValidationError(msg)
| _not_more_than_96_hours_in_future(dte, msg="Date cannot be more than 96hrs in the future"):
if dte > datetime.utcnow() + timedelta(hours=96):
raise ValidationError(msg)
def _validate_not_in_past(dte, msg="Date cannot be in the past"):
| 64 | 64 | 33 | 19 | 45 | TechforgoodCAST/notifications-api | app/schemas.py | Python | _validate_not_in_past | _validate_not_in_past | 47 | 49 | 47 | 47 | 1da2c4577d9a8c1e651394667f05708ae0a10948 | bigcode/the-stack | train |
b80069cd48dd2c22ce270ab2 | train | class | class SmsTemplateNotificationSchema(SmsNotificationSchema):
template = fields.Str(required=True)
job = fields.String()
| class SmsTemplateNotificationSchema(SmsNotificationSchema):
| template = fields.Str(required=True)
job = fields.String()
| to = fields.Str(required=True)
template = fields.Str(required=True)
@validates('to')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
raise ValidationError(str(e))
class SmsTemplateNotificationSchema(SmsNotificationSche... | 64 | 64 | 24 | 10 | 54 | TechforgoodCAST/notifications-api | app/schemas.py | Python | SmsTemplateNotificationSchema | SmsTemplateNotificationSchema | 524 | 526 | 524 | 524 | 9247efc459aab3a20d8f1315de01d6f36e004f9c | bigcode/the-stack | train |
72e087dd7a704d4625ebc479 | train | class | class UserSchema(BaseSchema):
permissions = fields.Method("user_permissions", dump_only=True)
password_changed_at = field_for(models.User, 'password_changed_at', format=DATETIME_FORMAT_NO_TIMEZONE)
created_at = field_for(models.User, 'created_at', format=DATETIME_FORMAT_NO_TIMEZONE)
auth_type = field_f... | class UserSchema(BaseSchema):
| permissions = fields.Method("user_permissions", dump_only=True)
password_changed_at = field_for(models.User, 'password_changed_at', format=DATETIME_FORMAT_NO_TIMEZONE)
created_at = field_for(models.User, 'created_at', format=DATETIME_FORMAT_NO_TIMEZONE)
auth_type = field_for(models.User, 'auth_type')
... | __(*args, **kwargs)
@post_load
def make_instance(self, data):
"""Deserialize data to an instance of the model. Update an existing row
if specified in `self.instance` or loaded by primary key(s) in the data;
else create a new row.
:param data: Data to deserialize.
"""
... | 100 | 100 | 335 | 6 | 94 | TechforgoodCAST/notifications-api | app/schemas.py | Python | UserSchema | UserSchema | 99 | 146 | 99 | 100 | aa841adcee28141068696f2e50b99f9b65df4eb1 | bigcode/the-stack | train |
1e097d19cdd0f8150c50c11a | train | class | class NotificationModelSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.Notification
strict = True
exclude = ('_personalisation', 'job', 'service', 'template', 'api_key',)
status = fields.String(required=False)
| class NotificationModelSchema(BaseSchema):
| class Meta(BaseSchema.Meta):
model = models.Notification
strict = True
exclude = ('_personalisation', 'job', 'service', 'template', 'api_key',)
status = fields.String(required=False)
| _address',
'reply_to_email_addresses',
'returned_letters',
'service_notification_stats',
'service_provider_stats',
'service_sms_senders',
'sms_sender',
'template_statistics',
'templates',
'users',
've... | 64 | 64 | 55 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | NotificationModelSchema | NotificationModelSchema | 350 | 356 | 350 | 350 | fa9743faaed3d5e15e21876977834cfe4738bb70 | bigcode/the-stack | train |
7cda38a3c13bc0d5fdabf0fa | train | function | def _validate_positive_number(value, msg="Not a positive integer"):
try:
page_int = int(value)
except ValueError:
raise ValidationError(msg)
if page_int < 1:
raise ValidationError(msg)
| def _validate_positive_number(value, msg="Not a positive integer"):
| try:
page_int = int(value)
except ValueError:
raise ValidationError(msg)
if page_int < 1:
raise ValidationError(msg)
| validate_and_format_phone_number
)
from app import ma
from app import models
from app.models import ServicePermission
from app.dao.permissions_dao import permission_dao
from app.utils import DATETIME_FORMAT_NO_TIMEZONE, get_template_instance
def _validate_positive_number(value, msg="Not a positive integer"):
| 64 | 64 | 49 | 14 | 49 | TechforgoodCAST/notifications-api | app/schemas.py | Python | _validate_positive_number | _validate_positive_number | 33 | 39 | 33 | 33 | f0df30dbe7f76d619ade9f9b669e81342f8d3c27 | bigcode/the-stack | train |
4769b7a3f24bf58c2479624d | train | function | def _validate_datetime_not_more_than_96_hours_in_future(dte, msg="Date cannot be more than 96hrs in the future"):
if dte > datetime.utcnow() + timedelta(hours=96):
raise ValidationError(msg)
| def _validate_datetime_not_more_than_96_hours_in_future(dte, msg="Date cannot be more than 96hrs in the future"):
| if dte > datetime.utcnow() + timedelta(hours=96):
raise ValidationError(msg)
| try:
page_int = int(value)
except ValueError:
raise ValidationError(msg)
if page_int < 1:
raise ValidationError(msg)
def _validate_datetime_not_more_than_96_hours_in_future(dte, msg="Date cannot be more than 96hrs in the future"):
| 64 | 64 | 49 | 29 | 35 | TechforgoodCAST/notifications-api | app/schemas.py | Python | _validate_datetime_not_more_than_96_hours_in_future | _validate_datetime_not_more_than_96_hours_in_future | 42 | 44 | 42 | 42 | 283fa143b45cdd324d8ca64cbd2b125b26e7d7b3 | bigcode/the-stack | train |
5e1f0a5d324d8b96f8ff77ca | train | class | class EmailDataSchema(ma.Schema):
class Meta:
strict = True
email = fields.Str(required=True)
def __init__(self, partial_email=False):
super().__init__()
self.partial_email = partial_email
@validates('email')
def validate_email(self, value):
if self.partial_email:... | class EmailDataSchema(ma.Schema):
| class Meta:
strict = True
email = fields.Str(required=True)
def __init__(self, partial_email=False):
super().__init__()
self.partial_email = partial_email
@validates('email')
def validate_email(self, value):
if self.partial_email:
return
try:
... | (BaseSchema.Meta):
model = models.InvitedUser
strict = True
@validates('email_address')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
raise ValidationError(str(e))
class EmailDataSchema(ma.Schema):
| 64 | 64 | 96 | 7 | 57 | TechforgoodCAST/notifications-api | app/schemas.py | Python | EmailDataSchema | EmailDataSchema | 634 | 652 | 634 | 635 | d562cfd52828bd3e6d8c58a4d0ba1407d88501e2 | bigcode/the-stack | train |
fe2d0db432f03901112a8620 | train | class | class TemplateHistorySchema(BaseSchema):
reply_to = fields.Method("get_reply_to", allow_none=True)
reply_to_text = fields.Method("get_reply_to_text", allow_none=True)
process_type = field_for(models.Template, 'process_type')
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], ... | class TemplateHistorySchema(BaseSchema):
| reply_to = fields.Method("get_reply_to", allow_none=True)
reply_to_text = fields.Method("get_reply_to_text", allow_none=True)
process_type = field_for(models.Template, 'process_type')
created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True)
created_at = field_for... | 'subject',
'template_redacted',
'updated_at',
'version',
)
@pre_dump
def remove_content_for_non_broadcast_templates(self, template):
if template.template_type != models.BROADCAST_TYPE:
template.content = None
class TemplateHistorySchem... | 64 | 64 | 146 | 7 | 56 | TechforgoodCAST/notifications-api | app/schemas.py | Python | TemplateHistorySchema | TemplateHistorySchema | 420 | 436 | 420 | 421 | 8a78874b580acacc006329649545f7638c5162d1 | bigcode/the-stack | train |
a64a7391f91f1321e2099d2e | train | class | class UnarchivedTemplateSchema(BaseSchema):
archived = fields.Boolean(required=True)
@validates_schema
def validate_archived(self, data):
if data['archived']:
raise ValidationError('Template has been deleted', 'template')
| class UnarchivedTemplateSchema(BaseSchema):
| archived = fields.Boolean(required=True)
@validates_schema
def validate_archived(self, data):
if data['archived']:
raise ValidationError('Template has been deleted', 'template')
| expiry_date = fields.DateTime()
created_at = fields.DateTime()
updated_at = fields.DateTime()
created_by_id = fields.UUID()
class EventSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.Event
strict = True
class UnarchivedTemplateSchema(BaseSchema):
| 64 | 64 | 52 | 9 | 54 | TechforgoodCAST/notifications-api | app/schemas.py | Python | UnarchivedTemplateSchema | UnarchivedTemplateSchema | 731 | 737 | 731 | 731 | 4c8dbaab629da1fd374de5b61aae7ea8ada8d34a | bigcode/the-stack | train |
3e18ba0e4653d385035fdd1e | train | class | class NotificationWithTemplateSchema(BaseSchema):
class Meta(BaseSchema.Meta):
model = models.Notification
strict = True
exclude = ('_personalisation', 'scheduled_notification')
template = fields.Nested(
TemplateSchema,
only=[
'id',
'version',
... | class NotificationWithTemplateSchema(BaseSchema):
| class Meta(BaseSchema.Meta):
model = models.Notification
strict = True
exclude = ('_personalisation', 'scheduled_notification')
template = fields.Nested(
TemplateSchema,
only=[
'id',
'version',
'name',
'template_type',
... | @validates('to')
def validate_to(self, value):
try:
validate_email_address(value)
except InvalidEmailError as e:
raise ValidationError(str(e))
class SmsTemplateNotificationSchema(SmsNotificationSchema):
template = fields.Str(required=True)
job = fields.String()
... | 71 | 71 | 239 | 8 | 63 | TechforgoodCAST/notifications-api | app/schemas.py | Python | NotificationWithTemplateSchema | NotificationWithTemplateSchema | 529 | 562 | 529 | 529 | 157dc52d9c74e03f1f94ad86a65a35b02b8499c1 | bigcode/the-stack | train |
4d7634a35e8a28f311bfdc64 | train | function | def xlsx_doc_validate(document):
wb = openpyxl.load_workbook(document)
sheets = wb.sheetnames
validated_rows = []
invalid_rows = []
for sheet_name in sheets:
valid_data, invalid_data = get_validated_rows(
wb, sheet_name, validated_rows, invalid_rows
)
if isinstanc... | def xlsx_doc_validate(document):
| wb = openpyxl.load_workbook(document)
sheets = wb.sheetnames
validated_rows = []
invalid_rows = []
for sheet_name in sheets:
valid_data, invalid_data = get_validated_rows(
wb, sheet_name, validated_rows, invalid_rows
)
if isinstance(valid_data, dict):
... | = []
for row in data:
if row.get("email", None):
if re.match(email_regex, row.get("email", None)) is None:
invalid_rows.append(row)
else:
validated_rows.append(row)
return validated_rows, inv... | 64 | 64 | 128 | 7 | 56 | vftens/Django-CRM | marketing/forms.py | Python | xlsx_doc_validate | xlsx_doc_validate | 152 | 169 | 152 | 152 | 8e1e64e38650cd707f152c6fbbed55be18e6deaa | bigcode/the-stack | train |
707ad153b7ae0c314f58a278 | train | class | class EmailCampaignForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.obj_instance = kwargs.get("instance", None)
super(EmailCampaignForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs = {"class": "form-control"}
self... | class EmailCampaignForm(forms.ModelForm):
| def __init__(self, *args, **kwargs):
self.obj_instance = kwargs.get("instance", None)
super(EmailCampaignForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs = {"class": "form-control"}
self.fields["name"].required = True
se... | ):
title = self.cleaned_data.get("title")
if (
Campaign.objects.filter(title__iexact=title)
.exclude(id=self.instance.id)
.exists()
):
raise forms.ValidationError("Campaign with this title already exists.")
return title
class EmailCampaignF... | 64 | 64 | 189 | 8 | 55 | vftens/Django-CRM | marketing/forms.py | Python | EmailCampaignForm | EmailCampaignForm | 502 | 529 | 502 | 502 | 8ba1afd0d7d28cb3dfa6eae77b1fa1a1866b3202 | bigcode/the-stack | train |
eba6d3f5e2e1fab6a50206c2 | train | class | class ContactListForm(forms.ModelForm):
tags = forms.CharField(max_length=5000, required=False)
contacts_file = forms.FileField(required=False)
class Meta:
model = ContactList
fields = ["name"]
def __init__(self, *args, **kwargs):
super(ContactListForm, self).__init__(*args, **... | class ContactListForm(forms.ModelForm):
| tags = forms.CharField(max_length=5000, required=False)
contacts_file = forms.FileField(required=False)
class Meta:
model = ContactList
fields = ["name"]
def __init__(self, *args, **kwargs):
super(ContactListForm, self).__init__(*args, **kwargs)
self.fields["contacts_fi... | decode("ascii"))
document.seek(0, 0) # csv file
return csv_doc_validate(document)
except Exception as e:
print(e)
print("csv")
try:
return xlsx_doc_validate(document) # xlsx file
except Exception as e:
print(e)
print("xlsx")
... | 134 | 135 | 450 | 8 | 126 | vftens/Django-CRM | marketing/forms.py | Python | ContactListForm | ContactListForm | 249 | 302 | 249 | 249 | 5241cbecc1b2671f13365f63e2ace0325296f017 | bigcode/the-stack | train |
efd0a594e2b6cfe48555077a | train | class | class BlockedEmailForm(forms.ModelForm):
class Meta:
model = BlockedEmail
fields = [
"email",
]
def clean_email(self):
email = self.cleaned_data.get("email")
if (
BlockedEmail.objects.filter(email__iexact=email)
.exclude(id=self.instan... | class BlockedEmailForm(forms.ModelForm):
| class Meta:
model = BlockedEmail
fields = [
"email",
]
def clean_email(self):
email = self.cleaned_data.get("email")
if (
BlockedEmail.objects.filter(email__iexact=email)
.exclude(id=self.instance.id)
.exists()
):
... | .ValidationError("Enter a valid domain.")
if (
BlockedDomain.objects.filter(domain__iexact=domain)
.exclude(id=self.instance.id)
.exists()
):
raise forms.ValidationError("Domain with this name already exists.")
return domain
class BlockedEmailForm(... | 64 | 64 | 89 | 9 | 54 | vftens/Django-CRM | marketing/forms.py | Python | BlockedEmailForm | BlockedEmailForm | 553 | 568 | 553 | 553 | 2097d82b1f5e530f740431be1a2abb0a56d4e0d7 | bigcode/the-stack | train |
59fed50b21640420ccc66aca | train | class | class BlockedDomainsForm(forms.ModelForm):
class Meta:
model = BlockedDomain
fields = [
"domain",
]
def clean_domain(self):
domain = self.cleaned_data.get("domain")
domain_regex = "^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"
if re.match(domain_regex, doma... | class BlockedDomainsForm(forms.ModelForm):
| class Meta:
model = BlockedDomain
fields = [
"domain",
]
def clean_domain(self):
domain = self.cleaned_data.get("domain")
domain_regex = "^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"
if re.match(domain_regex, domain) is None:
raise forms.Valida... | (self):
email = self.cleaned_data.get("email")
if (
ContactEmailCampaign.objects.filter(email=email)
.exclude(id=self.instance.id)
.exists()
):
raise forms.ValidationError("Contact with this Email already exists.")
return email
class Blocke... | 64 | 64 | 147 | 9 | 54 | vftens/Django-CRM | marketing/forms.py | Python | BlockedDomainsForm | BlockedDomainsForm | 532 | 550 | 532 | 532 | 78bd949f0be4fb366094a33c6dcdb9f4477af2c5 | bigcode/the-stack | train |
eab6c916f6bfb0b7d83fecae | train | function | def xls_doc_validate(document):
wb = xlrd.open_workbook(file_contents=document.open().read())
sheets = wb.sheet_names()
validated_rows = []
invalid_rows = []
for sheet_name in sheets:
valid_data, invalid_data = get_validated_rows_xls(
wb, sheet_name, validated_rows, invalid_rows
... | def xls_doc_validate(document):
| wb = xlrd.open_workbook(file_contents=document.open().read())
sheets = wb.sheet_names()
validated_rows = []
invalid_rows = []
for sheet_name in sheets:
valid_data, invalid_data = get_validated_rows_xls(
wb, sheet_name, validated_rows, invalid_rows
)
# if the data ... | = []
for row in data:
if row.get("email", None):
if re.match(email_regex, row.get("email", None)) is None:
invalid_rows.append(row)
else:
validated_rows.append(row)
return validated_rows, inv... | 64 | 64 | 152 | 7 | 56 | vftens/Django-CRM | marketing/forms.py | Python | xls_doc_validate | xls_doc_validate | 207 | 225 | 207 | 207 | bef2d656dc0768b20ffcbf4e654067275aab1df8 | bigcode/the-stack | train |
22cd6c93a51af996af92f880 | train | function | def csv_doc_validate(document):
temp_row = []
invalid_row = []
# this stores all the failed csv contacts
failed_contacts_csv = []
reader = csv.reader((document.read().decode("iso-8859-1")).splitlines())
# csv_headers = ["first name", "last name", "email"]
csv_headers = ["first name", "email"... | def csv_doc_validate(document):
| temp_row = []
invalid_row = []
# this stores all the failed csv contacts
failed_contacts_csv = []
reader = csv.reader((document.read().decode("iso-8859-1")).splitlines())
# csv_headers = ["first name", "last name", "email"]
csv_headers = ["first name", "email"]
# required_headers = ["fir... | import csv
import datetime
import re
import openpyxl
import xlrd
from django import forms
from marketing.models import (
BlockedDomain,
BlockedEmail,
Campaign,
Contact,
ContactEmailCampaign,
ContactList,
EmailTemplate,
)
# from haystack.forms import SearchForm
email_regex = r"(^[a-zA-Z0-... | 112 | 139 | 465 | 6 | 106 | vftens/Django-CRM | marketing/forms.py | Python | csv_doc_validate | csv_doc_validate | 24 | 75 | 24 | 24 | 0ceda67ffd98afeecef231c1199964a3f1fc6eac | bigcode/the-stack | train |
89a8c69067e741181bc07b26 | train | function | def get_validated_rows_xls(wb, sheet_name, validated_rows, invalid_rows):
wb_sheet = wb.sheet_by_name(sheet_name)
sheet_headers = [cell.value for cell in wb_sheet.row(0)]
required_headers = ["first name", "email"]
# this condition will check if the both fields in required_headers exist
if not len(s... | def get_validated_rows_xls(wb, sheet_name, validated_rows, invalid_rows):
| wb_sheet = wb.sheet_by_name(sheet_name)
sheet_headers = [cell.value for cell in wb_sheet.row(0)]
required_headers = ["first name", "email"]
# this condition will check if the both fields in required_headers exist
if not len(set(sheet_headers).intersection(required_headers)) == 2:
missing_he... | sheet_name, validated_rows, invalid_rows
)
if isinstance(valid_data, dict):
return valid_data
validated_rows = validated_rows + valid_data
invalid_rows = invalid_rows + invalid_data
return {
"error": False,
"validated_rows": validated_rows,
"inval... | 90 | 90 | 300 | 19 | 71 | vftens/Django-CRM | marketing/forms.py | Python | get_validated_rows_xls | get_validated_rows_xls | 172 | 204 | 172 | 172 | c94f02d15910e4c3b88c2226b80d1117c72d2b66 | bigcode/the-stack | train |
5a5acc6fbeee02aaa7e970ad | train | class | class SendCampaignForm(forms.ModelForm):
schedule_later = forms.BooleanField(required=False)
reply_to_crm = forms.BooleanField(required=False)
timezone = forms.CharField(max_length=500, required=False)
schedule_date_time = forms.CharField(max_length=100, required=False)
reply_to_email = forms.EmailF... | class SendCampaignForm(forms.ModelForm):
| schedule_later = forms.BooleanField(required=False)
reply_to_crm = forms.BooleanField(required=False)
timezone = forms.CharField(max_length=500, required=False)
schedule_date_time = forms.CharField(max_length=100, required=False)
reply_to_email = forms.EmailField(max_length=100, required=False)
... | ")
# data = import_document_validator(document)
# if data.get("error"):
# raise forms.ValidationError(data.get("message"))
# else:
# self.validated_rows = data.get("validated_rows")
# return document
# def clean_contact_list(self):
# contact_list = se... | 204 | 205 | 686 | 8 | 196 | vftens/Django-CRM | marketing/forms.py | Python | SendCampaignForm | SendCampaignForm | 416 | 499 | 416 | 416 | 304e3371f9f61644689261e33b4239140bcf9e49 | bigcode/the-stack | train |
65bb5c81f8f367a4d018dfd3 | train | class | class EmailTemplateForm(forms.ModelForm):
class Meta:
model = EmailTemplate
fields = ["title", "subject", "html"]
| class EmailTemplateForm(forms.ModelForm):
| class Meta:
model = EmailTemplate
fields = ["title", "subject", "html"]
| of the Contact List")
# else:
# for each in json.loads(contact_list):
# if not ContactList.objects.filter(id=each).first():
# raise forms.ValidationError(
# "Please choose a valid Contact List")
# return contact_list
class EmailTe... | 64 | 64 | 30 | 8 | 55 | vftens/Django-CRM | marketing/forms.py | Python | EmailTemplateForm | EmailTemplateForm | 410 | 413 | 410 | 410 | f7bee8ddee0affc740261ede6c9fa56e9d3cac05 | bigcode/the-stack | train |
8211bbf9eaf4a6c2eefe84e9 | train | class | class ContactForm(forms.ModelForm):
contact_list = forms.CharField(max_length=5000)
def __init__(self, *args, **kwargs):
# request_user = kwargs.pop("request_user", None)
self.obj_instance = kwargs.get("instance", None)
super(ContactForm, self).__init__(*args, **kwargs)
for fiel... | class ContactForm(forms.ModelForm):
| contact_list = forms.CharField(max_length=5000)
def __init__(self, *args, **kwargs):
# request_user = kwargs.pop("request_user", None)
self.obj_instance = kwargs.get("instance", None)
super(ContactForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
... | visible_to = visible_to.exclude(
# email__in=instance_visible_to)
# if visible_to:
# raise forms.ValidationError(
# str(each) + ' User aleady existed')
# return self.data['visible_to']
# raise forms.... | 78 | 78 | 260 | 7 | 71 | vftens/Django-CRM | marketing/forms.py | Python | ContactForm | ContactForm | 324 | 358 | 324 | 324 | af31d97c562149199da9b414176177b4c6e61092 | bigcode/the-stack | train |
4fb5ccdce800c0b3335d36ae | train | function | def import_document_validator(document):
try:
# dialect = csv.Sniffer().sniff(document.read(1024).decode("ascii"))
document.seek(0, 0) # csv file
return csv_doc_validate(document)
except Exception as e:
print(e)
print("csv")
try:
return xlsx_doc_valid... | def import_document_validator(document):
| try:
# dialect = csv.Sniffer().sniff(document.read(1024).decode("ascii"))
document.seek(0, 0) # csv file
return csv_doc_validate(document)
except Exception as e:
print(e)
print("csv")
try:
return xlsx_doc_validate(document) # xlsx file
except... | (valid_data) == dict:
return valid_data
validated_rows = validated_rows + valid_data
invalid_rows = invalid_rows + invalid_data
return {
"error": False,
"validated_rows": validated_rows,
"invalid_rows": invalid_rows,
}
def import_document_v... | 64 | 64 | 151 | 6 | 58 | vftens/Django-CRM | marketing/forms.py | Python | import_document_validator | import_document_validator | 228 | 246 | 228 | 228 | 410f9842b995807bd60dd8ec4f61f79377518f03 | bigcode/the-stack | train |
6a17717b270f2b397e93e571 | train | function | def get_validated_rows(wb, sheet_name, validated_rows, invalid_rows):
wb_sheet = wb[sheet_name]
sheet_headers = [cell.value for cell in wb_sheet[1]]
required_headers = ["first name", "email"]
# this condition will check if the both fields in required_headers exist
if not len(set(sheet_headers).inte... | def get_validated_rows(wb, sheet_name, validated_rows, invalid_rows):
| wb_sheet = wb[sheet_name]
sheet_headers = [cell.value for cell in wb_sheet[1]]
required_headers = ["first name", "email"]
# this condition will check if the both fields in required_headers exist
if not len(set(sheet_headers).intersection(required_headers)) == 2:
missing_headers = set(requir... | [x_index])
# temp_row.append(cell.value)
# if len(invalid_row) > 0:
# invalid_rows.append(temp_row)
# else:
# if len(temp_row) >= len(required_headers):
# validated_rows.append(temp_row)
# return validated_rows, invalid_rows... | 81 | 81 | 270 | 17 | 63 | vftens/Django-CRM | marketing/forms.py | Python | get_validated_rows | get_validated_rows | 120 | 149 | 120 | 120 | 9fbcbd3f24ba2094945beb3a76e75ed412ef7db1 | bigcode/the-stack | train |
59c8db94644db51b2b068a8c | train | function | def write(file, content, mode='a'):
"""
Writes content to a file
:param mode: File mode either 'a' or 'w'
:param file: file name
:param content:content to be written onto file
:return:
"""
f = open(file, mode)
f.write(content)
f.close()
| def write(file, content, mode='a'):
| """
Writes content to a file
:param mode: File mode either 'a' or 'w'
:param file: file name
:param content:content to be written onto file
:return:
"""
f = open(file, mode)
f.write(content)
f.close()
| ='ignore')
def normalize(a):
"""
Calculates Z score
:param a: Array to be normalized
:return: Normalized Array
"""
a = (a - np.mean(a)) / (np.std(a))
return a
def write(file, content, mode='a'):
| 64 | 64 | 77 | 10 | 53 | parampopat/COVID19 | eda.py | Python | write | write | 27 | 37 | 27 | 27 | 2e4bc0a82a7569e4b0703df09839a3e0ab9980b1 | bigcode/the-stack | train |
063d22e0849f0770b6fd042f | train | function | def analyze(dataset, type, to_plot=False, labels=None, save_plot=True, save_csv=True):
"""
:param dataset: Dataset DataFrame
:param type: Type of cases
:param to_plot: True to plot
:param labels: Plotting labels
:param save_plot: True to save plots, False will show the plot
:param save_csv:... | def analyze(dataset, type, to_plot=False, labels=None, save_plot=True, save_csv=True):
| """
:param dataset: Dataset DataFrame
:param type: Type of cases
:param to_plot: True to plot
:param labels: Plotting labels
:param save_plot: True to save plots, False will show the plot
:param save_csv: True to save correlation data into CSV file
:return: Correlation Data
"""
... | 22/20')
plt.ylabel('Z-Score Normalized Count')
plt.legend()
if save:
savefile = ""
for label in labels:
savefile = savefile + label + '-'
plt.savefig(savefile + title + '.png', dpi=300)
plt.close()
else:
plt.show()
def analyze(dataset, type, to_plot=Fa... | 92 | 92 | 308 | 21 | 71 | parampopat/COVID19 | eda.py | Python | analyze | analyze | 126 | 156 | 126 | 126 | cfcefc045fdacb413520a8d05789249405987a33 | bigcode/the-stack | train |
43cdcebba97eb7b0fd00050f | train | function | def cross_corr(data, raw_data, to_write=False, file=None):
"""
Calculates Maximum Cross-Correlation and Delays.
:param file: File name
:param data: Dictionary of Data
:param to_write: True to write to a csv
:return:
"""
if to_write:
if file is None:
raise ValueError("... | def cross_corr(data, raw_data, to_write=False, file=None):
| """
Calculates Maximum Cross-Correlation and Delays.
:param file: File name
:param data: Dictionary of Data
:param to_write: True to write to a csv
:return:
"""
if to_write:
if file is None:
raise ValueError("Expected input for 'file'")
st = str("Country_1,Cou... | for country in count_by_dates[key].keys():
count_by_countries[country].append(count_by_dates[key][country])
# Z-Score Normalize the data
for key in count_by_countries.keys():
count_by_countries_norm[key] = normalize(count_by_countries[key])
return group_by_data, count_by_dates,... | 98 | 98 | 327 | 15 | 82 | parampopat/COVID19 | eda.py | Python | cross_corr | cross_corr | 69 | 98 | 69 | 69 | 7bd6381a7ef1fd83393a22762eb3daf9db1fe7fe | bigcode/the-stack | train |
537c3410af3992e7dfdd3636 | train | function | def arrange_data(data, dates, group_by='Country/Region'):
"""
Arranges data into dictionaries.
:param dates: List of dates over which data is to be truncated
:param data: Data DataFrame which is to be arranged
:param group_by: Column header over which data is to be grouped by
:return:
"""
... | def arrange_data(data, dates, group_by='Country/Region'):
| """
Arranges data into dictionaries.
:param dates: List of dates over which data is to be truncated
:param data: Data DataFrame which is to be arranged
:param group_by: Column header over which data is to be grouped by
:return:
"""
count_by_dates = {}
count_by_countries = defaultdict... | :param mode: File mode either 'a' or 'w'
:param file: file name
:param content:content to be written onto file
:return:
"""
f = open(file, mode)
f.write(content)
f.close()
def arrange_data(data, dates, group_by='Country/Region'):
| 72 | 72 | 243 | 14 | 58 | parampopat/COVID19 | eda.py | Python | arrange_data | arrange_data | 40 | 66 | 40 | 40 | 55625a5006ad7e8de3c11a28bf5c7a2be0a273ef | bigcode/the-stack | train |
3c1256c0b28de0f4ebf05b6e | train | function | def normalize(a):
"""
Calculates Z score
:param a: Array to be normalized
:return: Normalized Array
"""
a = (a - np.mean(a)) / (np.std(a))
return a
| def normalize(a):
| """
Calculates Z score
:param a: Array to be normalized
:return: Normalized Array
"""
a = (a - np.mean(a)) / (np.std(a))
return a
| popat/"
__data__ = "https://github.com/CSSEGISandData/COVID-19"
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
import json
np.seterr(divide='ignore', invalid='ignore')
def normalize(a):
| 64 | 64 | 51 | 4 | 60 | parampopat/COVID19 | eda.py | Python | normalize | normalize | 17 | 24 | 17 | 17 | 8b0c5abcf38b580eaf9fd6e117d9b149eb96f849 | bigcode/the-stack | train |
d6ce364d61ca1a5a5a34fe99 | train | function | def plot_data(labels, data, title='', save=False):
"""
Plots data
:param labels: List of data labels to plot
:param data: Data from which plot is to be generated
:param title: Title of the chart
:param save: True to save plot as a png file
:return:
"""
for label in labels:
pl... | def plot_data(labels, data, title='', save=False):
| """
Plots data
:param labels: List of data labels to plot
:param data: Data from which plot is to be generated
:param title: Title of the chart
:param save: True to save plot as a png file
:return:
"""
for label in labels:
plt.plot(data[label], label=label)
plt.title(titl... | raw_data[key][-1]) + "," + str(raw_data[key_1][-1]) + ',' + str(max_index) + "," + str(
rel_corr.max())
write(file=file, content="\n" + st)
return max_indices
def plot_data(labels, data, title='', save=False):
| 64 | 64 | 176 | 12 | 51 | parampopat/COVID19 | eda.py | Python | plot_data | plot_data | 101 | 123 | 101 | 101 | b528f8f9f3e059ec2d9f374fdad15d27067aba5d | bigcode/the-stack | train |
374bc21402299082fc22ca62 | train | function | def make_surrogate_array(nbsubj=10, dimx=30, dimy=30, sk=1.0,
noise_level=1.0, pos=pos, ampli=ampli,
spatial_jitter=1.0, signal_jitter=1.0,
width=5.0, out_text_file=None, out_image_file=None,
verbose=False, seed=False)... | def make_surrogate_array(nbsubj=10, dimx=30, dimy=30, sk=1.0,
noise_level=1.0, pos=pos, ampli=ampli,
spatial_jitter=1.0, signal_jitter=1.0,
width=5.0, out_text_file=None, out_image_file=None,
verbose=False, seed=False)... | """
Create surrogate (simulated) 2D activation data with spatial noise.
Parameters
-----------
nbsubj: integer, optionnal
The number of subjects, ie the number of different maps
generated.
dimx: integer, optionnal
The x size of the array returned.
dimy: integer
... | import numpy as np
import scipy.ndimage as nd
# definition of the maxima at the group level
pos = np.array([[6 , 7],
[10, 10],
[15, 10]])
ampli = np.array([3, 4, 4])
def _cone(shape, ij, pos, ampli, width):
"""
Define a cone of the proposed grid
"""
temp = np.zeros(sh... | 245 | 245 | 817 | 87 | 157 | yarikoptic/NiPy-OLD | nipy/neurospin/utils/simul_2d_multisubject_fmri_dataset.py | Python | make_surrogate_array | make_surrogate_array | 35 | 134 | 35 | 39 | 8c72a7d5670047a37451aa43f8815c8b1627d860 | bigcode/the-stack | train |
78c3fa91c0fb910c31a44f02 | train | function | def _cone(shape, ij, pos, ampli, width):
"""
Define a cone of the proposed grid
"""
temp = np.zeros(shape)
pos = np.reshape(pos,(1,2))
dist = np.sqrt(np.sum((ij-pos)**2, axis=1))
codi = (width-dist)*(dist < width)/width
temp[ij[:,0],ij[:,1]] = codi*ampli
return temp
| def _cone(shape, ij, pos, ampli, width):
| """
Define a cone of the proposed grid
"""
temp = np.zeros(shape)
pos = np.reshape(pos,(1,2))
dist = np.sqrt(np.sum((ij-pos)**2, axis=1))
codi = (width-dist)*(dist < width)/width
temp[ij[:,0],ij[:,1]] = codi*ampli
return temp
| nd
# definition of the maxima at the group level
pos = np.array([[6 , 7],
[10, 10],
[15, 10]])
ampli = np.array([3, 4, 4])
def _cone(shape, ij, pos, ampli, width):
| 64 | 64 | 97 | 13 | 51 | yarikoptic/NiPy-OLD | nipy/neurospin/utils/simul_2d_multisubject_fmri_dataset.py | Python | _cone | _cone | 23 | 32 | 23 | 23 | 9a34ff87b49a88db324cf06c9f43d2be6851ca3d | bigcode/the-stack | train |
f71a424c561082b4908cdbb9 | train | class | class TestNotificationModels(TestCase):
def create_test_data(self):
TestIdentityModels.create_test_data(self)
self.channel = Channel(user_id=self.worker.id)
self.channel.id = str(self.channel)
db.session.add(self.channel)
db.session.commit()
self.notification = Noti... | class TestNotificationModels(TestCase):
| def create_test_data(self):
TestIdentityModels.create_test_data(self)
self.channel = Channel(user_id=self.worker.id)
self.channel.id = str(self.channel)
db.session.add(self.channel)
db.session.commit()
self.notification = Notification(channel=self.channel,
... | #
# Memento
# Backend
# Unit Tests for Notification Models
#
from unittest import TestCase
from datetime import datetime
from ...app import db
from ...models import *
from .identity import TestIdentityModels
# unit tests for Notification models
class TestNotificationModels(TestCase):
| 60 | 64 | 156 | 7 | 52 | mrzzy/memento | src/backend/tests/models/notification.py | Python | TestNotificationModels | TestNotificationModels | 17 | 42 | 17 | 17 | 37a6c1082ed165f72b83f02d3bcaab90325dafbe | bigcode/the-stack | train |
fc8e8d112351a7558d534615 | train | function | def test_rdmo002_multi_outputs_on_single_component(dash_duo):
call_count = Value("i")
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value="dash"),
html.Div(html.Div(id="output"), id="output-container"),
]
)
@app.callback(
[... | def test_rdmo002_multi_outputs_on_single_component(dash_duo):
| call_count = Value("i")
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value="dash"),
html.Div(html.Div(id="output"), id="output-container"),
]
)
@app.callback(
[
Output("output", "children"),
Output(... | dash_duo.start_server(app)
btn = dash_duo.wait_for_element("#btn")
for click in range(1, 20):
btn.click()
for i in range(N_OUTPUTS):
dash_duo.wait_for_text_to_equal(
"#output-{}".format(i), "{}={}".format(i, i + click)
)
assert call_count.v... | 97 | 97 | 326 | 15 | 81 | loftwah/dash | tests/integration/renderer/test_multi_output.py | Python | test_rdmo002_multi_outputs_on_single_component | test_rdmo002_multi_outputs_on_single_component | 50 | 92 | 50 | 50 | 3221a2f511f0794efcb94bce6dfa199d7e4428aa | bigcode/the-stack | train |
43b5862e432438120f970c5b | train | function | def test_rdmo004_multi_output_circular_dependencies(dash_duo):
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Input(id="a"), dcc.Input(id="b"), html.P(id="c")])
@app.callback(Output("a", "value"), [Input("b", "value")])
def set_a(b):
return ((b or "") + "X")[:100]
@app.callback(
... | def test_rdmo004_multi_output_circular_dependencies(dash_duo):
| app = dash.Dash(__name__)
app.layout = html.Div([dcc.Input(id="a"), dcc.Input(id="b"), html.P(id="c")])
@app.callback(Output("a", "value"), [Input("b", "value")])
def set_a(b):
return ((b or "") + "X")[:100]
@app.callback(
[Output("b", "value"), Output("c", "children")], [Input("a"... | Input("input", "value")])
def update_output(value):
return ["out" + value]
dash_duo.start_server(app)
dash_duo.find_element("#input").send_keys("house")
dash_duo.wait_for_text_to_equal("#output", "outhouse")
def test_rdmo004_multi_output_circular_dependencies(dash_duo):
| 75 | 75 | 252 | 15 | 60 | loftwah/dash | tests/integration/renderer/test_multi_output.py | Python | test_rdmo004_multi_output_circular_dependencies | test_rdmo004_multi_output_circular_dependencies | 115 | 143 | 115 | 115 | f3972f8badfe7fd439f2a3c4e38ec2fdd9a41153 | bigcode/the-stack | train |
4cb0c2595907a5e1d14e825b | train | function | def test_rdmo003_single_output_as_multi(dash_duo):
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value=""),
html.Div(html.Div(id="output"), id="output-container"),
]
)
@app.callback([Output("output", "children")], [Input("input", "valu... | def test_rdmo003_single_output_as_multi(dash_duo):
| app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value=""),
html.Div(html.Div(id="output"), id="output-container"),
]
)
@app.callback([Output("output", "children")], [Input("input", "value")])
def update_output(value):
return ... | assert _html == (
'<div id="output" class="dash hello" '
'style="font-family: "dash hello";">dash hello</div>'
)
assert call_count.value == 7
def test_rdmo003_single_output_as_multi(dash_duo):
| 64 | 64 | 135 | 14 | 49 | loftwah/dash | tests/integration/renderer/test_multi_output.py | Python | test_rdmo003_single_output_as_multi | test_rdmo003_single_output_as_multi | 95 | 112 | 95 | 95 | 6fe7ebf8f50ffde3d225ed8b945f4a44ecd559f8 | bigcode/the-stack | train |
d68b9923acdbebf33bb6d3a3 | train | function | def test_rdmo005_set_props_behavior(dash_duo):
app = dash.Dash(__name__)
app.layout = html.Div(
[
dash_renderer_test_components.UncontrolledInput(id="id", value=""),
html.Div(
id="container",
children=dash_renderer_test_components.UncontrolledInput... | def test_rdmo005_set_props_behavior(dash_duo):
| app = dash.Dash(__name__)
app.layout = html.Div(
[
dash_renderer_test_components.UncontrolledInput(id="id", value=""),
html.Div(
id="container",
children=dash_renderer_test_components.UncontrolledInput(value=""),
),
]
)
... | is invoked no more than once.
dash_duo.wait_for_text_to_equal("#c", "X")
err_text = dash_duo.find_element("span.dash-fe-error__title").text
assert err_text == "Circular Dependencies"
def test_rdmo005_set_props_behavior(dash_duo):
| 64 | 64 | 183 | 13 | 51 | loftwah/dash | tests/integration/renderer/test_multi_output.py | Python | test_rdmo005_set_props_behavior | test_rdmo005_set_props_behavior | 146 | 170 | 146 | 146 | de437d744baf348461f9794704c6db0bc55a287a | bigcode/the-stack | train |
ca301a3279206b26e6f2e87a | train | function | def test_rdmo001_single_input_multi_outputs_on_multiple_components(dash_duo):
call_count = Value("i")
app = dash.Dash(__name__)
N_OUTPUTS = 50
app.layout = html.Div(
[html.Button("click me", id="btn")]
+ [html.Div(id="output-{}".format(i)) for i in range(N_OUTPUTS)]
)
@app.ca... | def test_rdmo001_single_input_multi_outputs_on_multiple_components(dash_duo):
| call_count = Value("i")
app = dash.Dash(__name__)
N_OUTPUTS = 50
app.layout = html.Div(
[html.Button("click me", id="btn")]
+ [html.Div(id="output-{}".format(i)) for i in range(N_OUTPUTS)]
)
@app.callback(
[Output("output-{}".format(i), "children") for i in range(N_OU... | from multiprocessing import Value
import dash
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
import dash_core_components as dcc
import dash_html_components as html
import dash_renderer_test_components
def test_rdmo001_single_input_multi_outputs_on_multiple_components(dash_duo):
| 61 | 77 | 258 | 17 | 43 | loftwah/dash | tests/integration/renderer/test_multi_output.py | Python | test_rdmo001_single_input_multi_outputs_on_multiple_components | test_rdmo001_single_input_multi_outputs_on_multiple_components | 12 | 47 | 12 | 12 | 1a1db4870a1d70d704dd427023a038287fff0d51 | bigcode/the-stack | train |
55a68edfa54eed8cf079b641 | train | class | class RecallCallback(BatchMetricCallback):
"""Recall score metric callback."""
def __init__(
self,
input_key: str = "targets",
output_key: str = "logits",
prefix: str = "recall",
activation: str = "Softmax",
per_class: bool = False,
class_args: List[str] ... | class RecallCallback(BatchMetricCallback):
| """Recall score metric callback."""
def __init__(
self,
input_key: str = "targets",
output_key: str = "logits",
prefix: str = "recall",
activation: str = "Softmax",
per_class: bool = False,
class_args: List[str] = None,
**kwargs,
):
""... | from typing import List
from catalyst.callbacks.metric import BatchMetricCallback
from catalyst.metrics.functional import (
wrap_class_metric2dict,
wrap_metric_fn_with_activation,
)
from catalyst.metrics.recall import recall
class RecallCallback(BatchMetricCallback):
| 51 | 111 | 371 | 8 | 42 | arjunshibu/catalyst | catalyst/callbacks/metrics/recall.py | Python | RecallCallback | RecallCallback | 11 | 56 | 11 | 11 | b90dfea2ebef9def72a25afbb22bf84b1d68283c | bigcode/the-stack | train |
aa70013cfeac3f97fe47883b | train | function | def get_arguments():
"""Get the command-line arguments.
This function sets up the argument parser. Returns a tuple containing
an object storing the argument values and a list of the file names
provided on command line.
"""
desc = """Compile, assemble, and link C files."""
parser = argparse.... | def get_arguments():
| """Get the command-line arguments.
This function sets up the argument parser. Returns a tuple containing
an object storing the argument values and a list of the file names
provided on command line.
"""
desc = """Compile, assemble, and link C files."""
parser = argparse.ArgumentParser(descri... | # -*- coding: utf-8 -*-
import argparse
import subprocess
import pathlib
import sys
from clexer import Lexer
from cparser import Parser
from cutils import *
from csyntax import Syntax
from casmgen import GenASM
def get_arguments():
| 55 | 64 | 112 | 4 | 50 | osskai/PythonSCC | main.py | Python | get_arguments | get_arguments | 14 | 27 | 14 | 14 | 0cb31dc31795c1d7d1327a87ae83cc4d676ab85e | bigcode/the-stack | train |
b652b88a83adddab33590983 | train | function | def find_library_or_err(file):
"""Search the given library file and return path if found.
If not found, add an error to the error collector and return None.
"""
path = find_library(file)
if not path:
comment = f"could not find {file}"
issue_collector.add(ErrorIssue(comment))
... | def find_library_or_err(file):
| """Search the given library file and return path if found.
If not found, add an error to the error collector and return None.
"""
path = find_library(file)
if not path:
comment = f"could not find {file}"
issue_collector.add(ErrorIssue(comment))
return None
else:
... | .o", "crt0.o"]:
crt = find_library(file)
if crt:
return crt
comment = "could not find crt0.o, crt1.o, or crt2.o for linking"
issue_collector.add(ErrorIssue(comment))
return None
def find_library_or_err(file):
| 64 | 64 | 81 | 7 | 56 | osskai/PythonSCC | main.py | Python | find_library_or_err | find_library_or_err | 163 | 174 | 163 | 163 | b61e5d9c6b2712892f69b988538db4be45738d67 | bigcode/the-stack | train |
db59178b1453d22c475a6375 | train | function | def assemble(asm_name, obj_name):
"""Assemble the given assembly file into an object file."""
try:
subprocess.check_call(["as", "-o", obj_name, asm_name])
except subprocess.CalledProcessError:
comment = "assembler returned non-zero status"
issue_collector.add(ErrorIssue(comment))
| def assemble(asm_name, obj_name):
| """Assemble the given assembly file into an object file."""
try:
subprocess.check_call(["as", "-o", obj_name, asm_name])
except subprocess.CalledProcessError:
comment = "assembler returned non-zero status"
issue_collector.add(ErrorIssue(comment))
| an error to the error collector and return None.
"""
path = find_library(file)
if not path:
comment = f"could not find {file}"
issue_collector.add(ErrorIssue(comment))
return None
else:
return path
def assemble(asm_name, obj_name):
| 64 | 64 | 68 | 9 | 54 | osskai/PythonSCC | main.py | Python | assemble | assemble | 177 | 183 | 177 | 177 | e3b3116f3cc6322943de1c35789c7c434b0ea121 | bigcode/the-stack | train |
83bbdeb8ab39f6c5d02b930d | train | function | def link(binary_name, obj_names):
"""Assemble the given object files into a binary."""
try:
crtnum = find_crtnum()
if not crtnum:
return
crti = find_library_or_err("crti.o")
if not crti:
return
linux_so = find_library_or_err("ld-linux-x86-64.so.2... | def link(binary_name, obj_names):
| """Assemble the given object files into a binary."""
try:
crtnum = find_crtnum()
if not crtnum:
return
crti = find_library_or_err("crti.o")
if not crti:
return
linux_so = find_library_or_err("ld-linux-x86-64.so.2")
if not linux_so:
... | semble the given assembly file into an object file."""
try:
subprocess.check_call(["as", "-o", obj_name, asm_name])
except subprocess.CalledProcessError:
comment = "assembler returned non-zero status"
issue_collector.add(ErrorIssue(comment))
def link(binary_name, obj_names):
| 64 | 64 | 180 | 8 | 56 | osskai/PythonSCC | main.py | Python | link | link | 186 | 213 | 186 | 186 | 3da4fa7e58c9d13ef870d86b43af9d1c21d239ff | bigcode/the-stack | train |
6c78b198762d5d0459e3a4b6 | train | function | def find_crtnum():
"""Search for the crt0, crt1, or crt2.o files on the system.
The crt1.o, crti.o, and crtn.o objects comprise the core CRT (C RunTime) objects required to
enable basic C programs to start and run.
crt1.o provides the _start symbol that the runtime linker, ld.so.1, jumps to in order to ... | def find_crtnum():
| """Search for the crt0, crt1, or crt2.o files on the system.
The crt1.o, crti.o, and crtn.o objects comprise the core CRT (C RunTime) objects required to
enable basic C programs to start and run.
crt1.o provides the _start symbol that the runtime linker, ld.so.1, jumps to in order to pass control
to... | ("/usr/local/lib"),
pathlib.Path("/lib"),
pathlib.Path("/usr/lib"),
pathlib.Path("/usr/x86_64-linux-gnu/lib64"),
pathlib.Path("/usr/x86_64-linux-gnu/lib")]
for path in search_paths:
full_path = path.joinpath(file)
if fu... | 87 | 87 | 292 | 6 | 80 | osskai/PythonSCC | main.py | Python | find_crtnum | find_crtnum | 139 | 160 | 139 | 139 | a3106781840df240329048a7788434dd78785c39 | bigcode/the-stack | train |
82f0494107749d6bd49e54b4 | train | function | def process_c_file(file, args):
"""Compile a C file into an object file and return the object file name."""
# 0. source code
code, source_code = read_file(file)
if not issue_collector.ok():
return None
# 1. lexer
tokens = Lexer(code)
# 2. parser
parser = Parser(tokens)
tree... | def process_c_file(file, args):
| """Compile a C file into an object file and return the object file name."""
# 0. source code
code, source_code = read_file(file)
if not issue_collector.ok():
return None
# 1. lexer
tokens = Lexer(code)
# 2. parser
parser = Parser(tokens)
tree = parser.parse()
if not iss... | file into object file and return the object file name."""
if file[-2:] == ".c":
return process_c_file(file, args)
elif file[-2:] == ".o":
return file
else:
comment = f"unknown file type: '{file}'"
issue_collector.add(ErrorIssue(comment))
def process_c_file(file, args):
| 77 | 77 | 259 | 8 | 69 | osskai/PythonSCC | main.py | Python | process_c_file | process_c_file | 72 | 112 | 72 | 72 | 668e9e7dfbe55e9725f9e40fd0b25590152ac85c | bigcode/the-stack | train |
027a06d0e7c40eda61454a2d | train | function | def write_asm(asm_source, asm_filename):
"""Save the given assembly source to disk at asm_filename.
asm_source (str) - Full assembly source code.
asm_filename (str) - Filename to which to save the generated assembly.
"""
try:
with open(asm_filename, "w") as s_file:
s_file.write... | def write_asm(asm_source, asm_filename):
| """Save the given assembly source to disk at asm_filename.
asm_source (str) - Full assembly source code.
asm_filename (str) - Filename to which to save the generated assembly.
"""
try:
with open(asm_filename, "w") as s_file:
s_file.write(asm_source)
except IOError:
... | for count, line in enumerate(c_file):
source_code[count] = line
return flat_text, source_code
except IOError:
comment = f"could not read file: '{file}'"
issue_collector.add(ErrorIssue(comment))
def write_asm(asm_source, asm_filename):
| 64 | 64 | 107 | 11 | 53 | osskai/PythonSCC | main.py | Python | write_asm | write_asm | 46 | 58 | 46 | 46 | f7742285ae15a577b32bc3cb0ac9a70ed311d53d | bigcode/the-stack | train |
f8f22a7302850546b766c411 | train | function | def find_library(file):
"""Search the given library file by searching in common directories.
If found, returns the path. Otherwise, returns None.
"""
search_paths = [pathlib.Path("/usr/local/lib/x86_64-linux-gnu"),
pathlib.Path("/lib/x86_64-linux-gnu"),
pathlib.P... | def find_library(file):
| """Search the given library file by searching in common directories.
If found, returns the path. Otherwise, returns None.
"""
search_paths = [pathlib.Path("/usr/local/lib/x86_64-linux-gnu"),
pathlib.Path("/lib/x86_64-linux-gnu"),
pathlib.Path("/usr/lib/x86_64-lin... | , asm_file)
if not issue_collector.ok():
return None
if sys.platform.startswith("darwin"):
# 5. machine code
assemble(asm_file, obj_file)
if not issue_collector.ok():
return None
return obj_file
def find_library(file):
| 64 | 64 | 188 | 5 | 58 | osskai/PythonSCC | main.py | Python | find_library | find_library | 115 | 136 | 115 | 115 | 0d9e659f8a19d58ef27a5b806e244d5e9b94fe9f | bigcode/the-stack | train |
f88d3209474f4944a5acaf8f | train | function | def read_file(file):
"""Return the contents of the given file."""
try:
source_code = {}
with open(file) as c_file:
flat_text = c_file.read()
c_file.seek(0)
for count, line in enumerate(c_file):
source_code[count] = line
return flat... | def read_file(file):
| """Return the contents of the given file."""
try:
source_code = {}
with open(file) as c_file:
flat_text = c_file.read()
c_file.seek(0)
for count, line in enumerate(c_file):
source_code[count] = line
return flat_text, source_code
... | Compile, assemble, and link C files."""
parser = argparse.ArgumentParser(description=desc, usage="scc [-h] [options] files...")
# Files to compile
parser.add_argument("files", metavar="files", nargs="+")
return parser.parse_args()
def read_file(file):
| 64 | 64 | 100 | 5 | 59 | osskai/PythonSCC | main.py | Python | read_file | read_file | 30 | 43 | 30 | 30 | 940c6ee6b4c8161c460bd54d7b7702dab9d2d98c | bigcode/the-stack | train |
8a158377cd6ced7bb534b3f3 | train | function | def process_file(file, args):
"""Process single file into object file and return the object file name."""
if file[-2:] == ".c":
return process_c_file(file, args)
elif file[-2:] == ".o":
return file
else:
comment = f"unknown file type: '{file}'"
issue_collector.add(ErrorIs... | def process_file(file, args):
| """Process single file into object file and return the object file name."""
if file[-2:] == ".c":
return process_c_file(file, args)
elif file[-2:] == ".o":
return file
else:
comment = f"unknown file type: '{file}'"
issue_collector.add(ErrorIssue(comment))
| assembly.
"""
try:
with open(asm_filename, "w") as s_file:
s_file.write(asm_source)
except IOError:
comment = f"could not write output file '{asm_filename}'"
issue_collector.add(ErrorIssue(comment))
def process_file(file, args):
| 64 | 64 | 80 | 7 | 57 | osskai/PythonSCC | main.py | Python | process_file | process_file | 61 | 69 | 61 | 61 | 48a5ae658fffff602f766fb73bc154b4b05a4377 | bigcode/the-stack | train |
a90b718a4bf3430b4d32453c | train | function | def main():
"""Run the main compiler script."""
"""
if not sys.platform.startswith("darwin"):
comment = "only x86_64 MacOs is supported"
issue_collector.add(ErrorIssue(comment))
return 1
"""
objs = []
"""
arguments = get_arguments()
for file in arguments.files:... | def main():
| """Run the main compiler script."""
"""
if not sys.platform.startswith("darwin"):
comment = "only x86_64 MacOs is supported"
issue_collector.add(ErrorIssue(comment))
return 1
"""
objs = []
"""
arguments = get_arguments()
for file in arguments.files:
obj... | to link
subprocess.check_call(
["ld", "-dynamic-linker", linux_so, crtnum, crti, "-lc"]
+ obj_names + [crtn, "-o", binary_name])
return True
except subprocess.CalledProcessError:
return False
def main():
| 64 | 64 | 165 | 3 | 60 | osskai/PythonSCC | main.py | Python | main | main | 216 | 245 | 216 | 216 | 9f0ac55d232be6decebe8a34dc62c2dc57509278 | bigcode/the-stack | train |
b9003a5c9c98cc2b66e6fd86 | train | class | class HigherRankOperator(tfkl.Layer):
""" Layer that applys an operation across multiple ranks like the batch size
This allows running something like a convolution over stimuli X neurons
by unrolling those two dimensions into a single batch axis. The Conv2D
operator expects the data to have... | class HigherRankOperator(tfkl.Layer):
| """ Layer that applys an operation across multiple ranks like the batch size
This allows running something like a convolution over stimuli X neurons
by unrolling those two dimensions into a single batch axis. The Conv2D
operator expects the data to have this format. The size is also determi... | ([[Ny, Nx]], dtype=inputs.dtype)
loc = tf.nn.sigmoid(loc) * dim_scale
scale = tf.nn.softplus(scale) + 1e-3
tf.debugging.assert_all_finite(loc, f'Guassian location broke')
tf.debugging.assert_all_finite(scale, f'Guassian location broke')
dist = tfp.distributions.TruncatedNormal(... | 119 | 119 | 398 | 8 | 111 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | HigherRankOperator | HigherRankOperator | 237 | 280 | 237 | 237 | 25ec0220473ca458769970f832bb31a42b35d4ea | bigcode/the-stack | train |
ea378e014d959ee939b1ca90 | train | function | def image_to_distribution(x):
params = image_to_gaussian(x)
loc, scale = tf.split(params, 2, axis=-1)
_, Ny, Nx, Nc = x.shape
# note we use (y,x) indexing to match indexing into images
dist = tfp.distributions.TruncatedNormal(loc=loc, scale=scale, low=0.0, high=[Ny, Nx])
return dist
| def image_to_distribution(x):
| params = image_to_gaussian(x)
loc, scale = tf.split(params, 2, axis=-1)
_, Ny, Nx, Nc = x.shape
# note we use (y,x) indexing to match indexing into images
dist = tfp.distributions.TruncatedNormal(loc=loc, scale=scale, low=0.0, high=[Ny, Nx])
return dist
| [0])
#tf.print(params[-1])
#tf.print(im[-1])
#tf.print(im_flatten[-1])
tf.debugging.assert_all_finite(params, f'Guassin parameters broke. {im_flatten[-1]}')
return params
def image_to_distribution(x):
| 64 | 64 | 92 | 6 | 57 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | image_to_distribution | image_to_distribution | 198 | 206 | 198 | 198 | 4f62dc2496962f634b68f2ad058c7ebc7bd83601 | bigcode/the-stack | train |
96a6b9c6134d3bbda3ccdbd6 | train | class | class CNN(ConvStack):
def __init__(self, architecture=None, padding='same', norm=None, l2_weight=1e-4, **kwargs):
# store for save and reconstruction
if architecture is None:
architecture = [[11, 32], [5, 32], [3, 32]]
self.l2_weight = l2_weight
self.architecture = archi... | class CNN(ConvStack):
| def __init__(self, architecture=None, padding='same', norm=None, l2_weight=1e-4, **kwargs):
# store for save and reconstruction
if architecture is None:
architecture = [[11, 32], [5, 32], [3, 32]]
self.l2_weight = l2_weight
self.architecture = architecture
self.pa... | is None:
pass
elif norm.lower() == 'batch':
# TODO: make sure BN on channel dimension is rotation equivariant
self.add(tfkl.BatchNormalization())
elif norm.lower() == 'layer':
self.add(tfkl.LayerNormalization(scale=True))
self.add(tfkl.Activation... | 73 | 74 | 249 | 6 | 67 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | CNN | CNN | 357 | 380 | 357 | 358 | bb3e8965443c270132b17cdb326bf415bfc2a06d | bigcode/the-stack | train |
0e8299283241862e0752f8b3 | train | class | class HeatmapToLocParams(tfkl.Layer):
def __init__(self, **kwargs):
super(HeatmapToLocParams, self).__init__(**kwargs)
self.param_regressor = tfk.Sequential([tfkl.Flatten(),
tfkl.Dense(4, bias_initializer=tf.initializers.zeros,
... | class HeatmapToLocParams(tfkl.Layer):
| def __init__(self, **kwargs):
super(HeatmapToLocParams, self).__init__(**kwargs)
self.param_regressor = tfk.Sequential([tfkl.Flatten(),
tfkl.Dense(4, bias_initializer=tf.initializers.zeros,
acti... | 2, axis=-1)
_, Ny, Nx, Nc = x.shape
# note we use (y,x) indexing to match indexing into images
dist = tfp.distributions.TruncatedNormal(loc=loc, scale=scale, low=0.0, high=[Ny, Nx])
return dist
class HeatmapToLocParams(tfkl.Layer):
| 78 | 78 | 262 | 10 | 67 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | HeatmapToLocParams | HeatmapToLocParams | 209 | 234 | 209 | 209 | ad1004a9e84f3273f4ca54dfa343c765446963ae | bigcode/the-stack | train |
d790c5c447bb76434ca5620e | train | class | class ConvStack(tfk.Sequential):
def __init__(self, architecture, **kwargs):
super(ConvStack, self).__init__(**kwargs)
for layer in architecture:
if len(layer) == 5:
depth, width, stride, norm, kwargs = layer
elif len(layer) == 4:
depth, wid... | class ConvStack(tfk.Sequential):
| def __init__(self, architecture, **kwargs):
super(ConvStack, self).__init__(**kwargs)
for layer in architecture:
if len(layer) == 5:
depth, width, stride, norm, kwargs = layer
elif len(layer) == 4:
depth, width, stride, kwargs = layer
... | output from operator
_, *new_dims = y.shape
# and unfold back out
y = tf.keras.backend.reshape(y, [-1, *dims[1:-self.op_rank], *new_dims])
return y
_activation = tfkl.ELU
class ConvStack(tfk.Sequential):
| 64 | 64 | 199 | 7 | 56 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | ConvStack | ConvStack | 286 | 311 | 286 | 287 | b958445c778c4b99cdf3ba0cbdd39a0f15d065d2 | bigcode/the-stack | train |
302fa59b1fb38892f5aa8971 | train | function | def image_to_gaussian(im, dtype=tf.float32):
im = tf.cast(im, dtype=dtype)
im.shape.assert_is_compatible_with([None, None, None, 1])
tf.debugging.assert_all_finite(im, 'Received bad image to parameterize')
_, Ny, Nx, Nc = im.shape
im_flatten = tf.reshape(im, [-1, Nx * Ny])
#im_flatten = (im_f... | def image_to_gaussian(im, dtype=tf.float32):
| im = tf.cast(im, dtype=dtype)
im.shape.assert_is_compatible_with([None, None, None, 1])
tf.debugging.assert_all_finite(im, 'Received bad image to parameterize')
_, Ny, Nx, Nc = im.shape
im_flatten = tf.reshape(im, [-1, Nx * Ny])
#im_flatten = (im_flatten - tf.reduce_min(im_flatten, axis=-1, k... | g.shape
# at this point responses is batch_size X stimuli x N
r = tf.expand_dims(tf.expand_dims(tf.expand_dims(responses, axis=3), axis=4), axis=5)
r = tf.tile(r, [1, 1, 1, nx, ny, 1])
# Finally concatenate out response
if self.sta_feature:
gr = tf.concat([g, g*r, ... | 131 | 131 | 439 | 12 | 118 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | image_to_gaussian | image_to_gaussian | 159 | 195 | 159 | 159 | 6efbde5412cab5bf4b7d428b2d2108df4ae7f3d9 | bigcode/the-stack | train |
27b9989264a00e5490dd1d4b | train | class | class ConvResponseConcatenate(tfkl.Layer):
def __init__(self, sta_feature=True, **kwargs):
self.sta_feature = sta_feature
self.response_shape = None
self.conv_shape = None
super(ConvResponseConcatenate, self).__init__(**kwargs)
def build(self, input_shapes):
self.respons... | class ConvResponseConcatenate(tfkl.Layer):
| def __init__(self, sta_feature=True, **kwargs):
self.sta_feature = sta_feature
self.response_shape = None
self.conv_shape = None
super(ConvResponseConcatenate, self).__init__(**kwargs)
def build(self, input_shapes):
self.response_shape, self.conv_shape = input_shapes
... | .cumsum(x, axis=self.axis, exclusive=True)
Ncount = tf.linspace(1e-5, tf.cast(N-1, tf.float32), N)
count_shape = [1] * len(input.shape)
count_shape[self.axis] = N
N = tf.reshape(Ncount, count_shape)
# normalize by the number of elements summed
x = tf.cast... | 134 | 134 | 448 | 9 | 124 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | ConvResponseConcatenate | ConvResponseConcatenate | 112 | 156 | 112 | 112 | 2ffce23f35ffdb0f6204c5cfd18c13292527a292 | bigcode/the-stack | train |
cbc2ce664fd7cf73eee3b89c | train | class | class Predictor(tfk.Model):
def __init__(self,
sta_feature=True,
cummulative=False,
laplace_weight=0.0,
cell_latent_dim=10,
l2_weight=0.01,
activity_weight=0.0,
architecture=[[11, 32], [5, 32], [3... | class Predictor(tfk.Model):
| def __init__(self,
sta_feature=True,
cummulative=False,
laplace_weight=0.0,
cell_latent_dim=10,
l2_weight=0.01,
activity_weight=0.0,
architecture=[[11, 32], [5, 32], [3, 32], 'same', "none"],
... |
class CNN(ConvStack):
def __init__(self, architecture=None, padding='same', norm=None, l2_weight=1e-4, **kwargs):
# store for save and reconstruction
if architecture is None:
architecture = [[11, 32], [5, 32], [3, 32]]
self.l2_weight = l2_weight
self.architecture = ar... | 256 | 256 | 2,357 | 6 | 250 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | Predictor | Predictor | 383 | 610 | 383 | 384 | 58c3ed64ef94bf35e1ee2e7cee8611024c10c5f3 | bigcode/the-stack | train |
b6d7bbcd3a97b4841379a08b | train | function | def test_compile_save():
neurons = 32
image_shape = [64, 34, 1]
inputs = [tfk.Input([neurons], name='responses'), tfk.Input(image_shape, name='stimuli')]
predictor = Predictor()
pred = predictor(inputs)
model = tfk.Model(inputs, pred)
optimizer = tf.optimizers.Adam(learning_rate=1e-2, clip... | def test_compile_save():
| neurons = 32
image_shape = [64, 34, 1]
inputs = [tfk.Input([neurons], name='responses'), tfk.Input(image_shape, name='stimuli')]
predictor = Predictor()
pred = predictor(inputs)
model = tfk.Model(inputs, pred)
optimizer = tf.optimizers.Adam(learning_rate=1e-2, clipnorm=10)
model.compi... | , 1e3))
dist = tfd.MixtureSameFamily(tfd.Categorical(probs=[1.0/self.samples] * self.samples),
components_distribution=dist)
return dist
return tfpl.DistributionLambda(make_distribution_fn=lambda s: multiple_samples_mixture_distribution(s),
... | 81 | 81 | 270 | 5 | 76 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | test_compile_save | test_compile_save | 613 | 649 | 613 | 613 | da6a8f9afb02c027277c5bda49d96f65911cd48f | bigcode/the-stack | train |
d75525397b922cc1844f3982 | train | class | class DeepSetSimple(tfkl.Layer):
"""DeepSet layer that computes the set collapse of all other elements"""
def __init__(self, cummulative, axis=1, **kwargs):
super(DeepSetSimple, self).__init__(**kwargs)
self.cummulative = cummulative
self.axis = axis
def call(self, input):
... | class DeepSetSimple(tfkl.Layer):
| """DeepSet layer that computes the set collapse of all other elements"""
def __init__(self, cummulative, axis=1, **kwargs):
super(DeepSetSimple, self).__init__(**kwargs)
self.cummulative = cummulative
self.axis = axis
def call(self, input):
x = tf.cast(input, tf.float64)
... | ))
weights = self.bias_L - tf.exp(-(tf.square(X) + tf.square(Y)) / 2 / tf.square(self.sigma_L))
filtered_weights = tf.nn.conv2d(x_unwrapped, self.laplace_filter,
padding='SAME', strides=1)
return super(LaplaceL2Regularizer, self).__call__(filtered_weight... | 93 | 93 | 310 | 8 | 85 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | DeepSetSimple | DeepSetSimple | 75 | 109 | 75 | 75 | 2aeb33dfd4438ada2e6ad40554e6e636a34c5c18 | bigcode/the-stack | train |
b839ff83469776e9d6e377d5 | train | class | class SE2CNN(tf.keras.Sequential):
def __init__(self, architecture, l2_weight=0.01, nb_orientations=8, padding='same', norm=None, dense=True, **kwargs):
super(SE2CNN, self).__init__(**kwargs)
regularizer = tfk.regularizers.l2(l2_weight)
for i, (k, c) in enumerate(list(architecture[:-1])):... | class SE2CNN(tf.keras.Sequential):
| def __init__(self, architecture, l2_weight=0.01, nb_orientations=8, padding='same', norm=None, dense=True, **kwargs):
super(SE2CNN, self).__init__(**kwargs)
regularizer = tfk.regularizers.l2(l2_weight)
for i, (k, c) in enumerate(list(architecture[:-1])):
if i == 0:
... | None
else:
depth, width, stride = layer
norm = None
kwargs = {}
use_bias = True if norm is None else norm.lower() == 'batch'
self.add(tfkl.Conv2D(depth, width, use_bias=use_bias, strides=stride, **kwargs))
if norm is None:... | 124 | 124 | 416 | 8 | 116 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | SE2CNN | SE2CNN | 314 | 354 | 314 | 315 | 905f9420f575ed8c0ec8e635f79ff2b7a5efe4ee | bigcode/the-stack | train |
9ecd1ed44ae8f35e4e7c879b | train | class | class LaplaceL2Regularizer(tf.keras.regularizers.L1L2):
def __init__(self, sigma_L=5.0, bias_L=1.0, **kwargs):
super(LaplaceL2Regularizer, self).__init__(**kwargs)
self.laplace_filter = tf.constant([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], dtype=tf.float32)[..., None, None]
self.sigma_L = tf.c... | class LaplaceL2Regularizer(tf.keras.regularizers.L1L2):
| def __init__(self, sigma_L=5.0, bias_L=1.0, **kwargs):
super(LaplaceL2Regularizer, self).__init__(**kwargs)
self.laplace_filter = tf.constant([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], dtype=tf.float32)[..., None, None]
self.sigma_L = tf.constant(sigma_L, dtype=tf.float32)
self.bias_L = ... | .
"""
import tensorflow as tf
import tensorflow_probability as tfp
from .util import interpolate_bilinear
from .se2cnn.layers import SE2Lifting, SE2GroupConv, SE2ProjCat, SE2ProjMax, SE2GroupSeparableConv
tfk = tf.keras
tfkl = tf.keras.layers
tfpl = tfp.layers
tfd = tfp.distributions
class LaplaceL2Regularizer(tf.ke... | 102 | 102 | 343 | 17 | 84 | sinzlab/fnp_neurips2020 | tuning_manifold/fnp_model.py | Python | LaplaceL2Regularizer | LaplaceL2Regularizer | 53 | 72 | 53 | 54 | 03acb1fbef439e0c8400d9c6ba0d652ba53d7607 | bigcode/the-stack | train |
a82b8e4d8c0b6d0cdd33cb17 | train | function | def test_TCorrMap_inputs():
input_map = dict(
absolute_threshold=dict(
argstr='-Thresh %f %s',
name_source='in_file',
suffix='_thresh',
xor=('absolute_threshold', 'var_absolute_threshold',
'var_absolute_threshold_normalize'),
),
... | def test_TCorrMap_inputs():
| input_map = dict(
absolute_threshold=dict(
argstr='-Thresh %f %s',
name_source='in_file',
suffix='_thresh',
xor=('absolute_threshold', 'var_absolute_threshold',
'var_absolute_threshold_normalize'),
),
args=dict(argstr='%s', ),
... | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrMap
def test_TCorrMap_inputs():
| 40 | 256 | 870 | 7 | 32 | moloney/nipype | nipype/interfaces/afni/tests/test_auto_TCorrMap.py | Python | test_TCorrMap_inputs | test_TCorrMap_inputs | 6 | 131 | 6 | 6 | d85d1b8e6e609453771cd560b32eb7b33092f48c | bigcode/the-stack | train |
a938974c05cfb0753b9ab537 | train | function | def test_TCorrMap_outputs():
output_map = dict(
absolute_threshold=dict(),
average_expr=dict(),
average_expr_nonzero=dict(),
correlation_maps=dict(),
correlation_maps_masked=dict(),
histogram=dict(),
mean_file=dict(),
pmean=dict(),
qmean=dict()... | def test_TCorrMap_outputs():
| output_map = dict(
absolute_threshold=dict(),
average_expr=dict(),
average_expr_nonzero=dict(),
correlation_maps=dict(),
correlation_maps_masked=dict(),
histogram=dict(),
mean_file=dict(),
pmean=dict(),
qmean=dict(),
sum_expr=dict(),
... | ',
suffix='_zmean',
),
)
inputs = TCorrMap.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_TCorrMap_outputs():
| 64 | 64 | 133 | 7 | 56 | moloney/nipype | nipype/interfaces/afni/tests/test_auto_TCorrMap.py | Python | test_TCorrMap_outputs | test_TCorrMap_outputs | 132 | 152 | 132 | 132 | 9514a54315734327b310adb604e13a7baf06b749 | bigcode/the-stack | train |
a8687b81a9c47b01b5b89d8a | train | class | @register_model("ConvKB", {'num_filters': 32, 'filter_sizes': [1], 'dropout': 0.1})
class ConvKB(EmbeddingModel):
r"""Convolution-based model
The ConvKB model :cite:`Nguyen2018`:
.. math::
f_{ConvKB}= concat \,(g \, ([\mathbf{e}_s, \mathbf{r}_p, \mathbf{e}_o]) * \Omega)) \cdot W
where :math:... | @register_model("ConvKB", {'num_filters': 32, 'filter_sizes': [1], 'dropout': 0.1})
class ConvKB(EmbeddingModel):
| r"""Convolution-based model
The ConvKB model :cite:`Nguyen2018`:
.. math::
f_{ConvKB}= concat \,(g \, ([\mathbf{e}_s, \mathbf{r}_p, \mathbf{e}_o]) * \Omega)) \cdot W
where :math:`g` is a non-linear function, :math:`*` is the convolution operator,
:math:`\cdot` is the dot product, :math:... | # Copyright 2019-2021 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import numpy as np
import tensorflow as tf
import logging
from .EmbeddingModel... | 172 | 256 | 4,805 | 37 | 135 | chauvu/AmpliGraph | ampligraph/latent_features/models/ConvKB.py | Python | ConvKB | ConvKB | 21 | 503 | 21 | 22 | cb5018ff0c2b6be4e037f046f3f639b2a131ee49 | bigcode/the-stack | train |
17fc0305e0dab44984387d51 | train | class | class Jobs(Requester):
"""
The jobs endpoint is used to query the status of existing
jobs in Nomad and to register new jobs.
By default, the agent's local region is used.
https://www.nomadproject.io/docs/http/jobs.html
"""
ENDPOINT = "jobs"
def __init__(self, **kwargs):
super(... | class Jobs(Requester):
| """
The jobs endpoint is used to query the status of existing
jobs in Nomad and to register new jobs.
By default, the agent's local region is used.
https://www.nomadproject.io/docs/http/jobs.html
"""
ENDPOINT = "jobs"
def __init__(self, **kwargs):
super(Jobs, self).__init__(**k... | import nomad.api.exceptions
from nomad.api.base import Requester
class Jobs(Requester):
| 20 | 213 | 711 | 5 | 14 | rndmh3ro/python-nomad | nomad/api/jobs.py | Python | Jobs | Jobs | 6 | 106 | 6 | 7 | 07144d111f11d98f35a7f0e56db030b36bd523a6 | bigcode/the-stack | train |
cf1df25638d54e03221a9e41 | train | function | def brute_force_search(blob, word):
blob_view = memoryview(blob)
word_view = memoryview(word)
n, m = len(blob), len(word)
end = n - m
results = []
i = 0
cnt = 0
while i <= end:
if match_word(blob_view, word_view, i, m):
prev_line_end = find_previous_line_end(blob_view... | def brute_force_search(blob, word):
| blob_view = memoryview(blob)
word_view = memoryview(word)
n, m = len(blob), len(word)
end = n - m
results = []
i = 0
cnt = 0
while i <= end:
if match_word(blob_view, word_view, i, m):
prev_line_end = find_previous_line_end(blob_view, i)
cur_line_end = find... | _end, find_previous_line_end
def match_word(blob, word, offset, m):
i = 0
while i < m:
if blob[offset + i] != word[i]:
break
i += 1
return i == m
def brute_force_search(blob, word):
| 64 | 64 | 172 | 8 | 55 | t2y/python-study | SearchString/brute_force_search.py | Python | brute_force_search | brute_force_search | 26 | 45 | 26 | 26 | 5951885bde635535237464e467ed951cf2f26e1c | bigcode/the-stack | train |
bce02982c13c6ab6b6696ecb | train | function | def match_word(blob, word, offset, m):
i = 0
while i < m:
if blob[offset + i] != word[i]:
break
i += 1
return i == m
| def match_word(blob, word, offset, m):
| i = 0
while i < m:
if blob[offset + i] != word[i]:
break
i += 1
return i == m
| www.geocities.jp/m_hiroi/light/pyalgo11.html
"""
import logging
import statistics
import sys
import timeit
from utils import log
from utils import parse_argument
from utils import find_current_line_end, find_previous_line_end
def match_word(blob, word, offset, m):
| 64 | 64 | 49 | 11 | 52 | t2y/python-study | SearchString/brute_force_search.py | Python | match_word | match_word | 17 | 23 | 17 | 17 | 21362e85c9a8d2ffcd5179c0e8f336bd59087f6a | bigcode/the-stack | train |
b85868f823c5d235f1c8a886 | train | function | def main():
args = parse_argument()
byte_word = args.word.encode('utf-8')
log.info('検索語: %s' % args.word)
log.info('検索語のバイト長: %d' % len(byte_word))
if args.measure:
log.setLevel(logging.ERROR)
with args.data() as blob:
results = brute_force_search(blob, byte_word)
for resu... | def main():
| args = parse_argument()
byte_word = args.word.encode('utf-8')
log.info('検索語: %s' % args.word)
log.info('検索語のバイト長: %d' % len(byte_word))
if args.measure:
log.setLevel(logging.ERROR)
with args.data() as blob:
results = brute_force_search(blob, byte_word)
for result in result... | blob_view[prev_line_end:cur_line_end].tobytes()
results.append(line)
i = cur_line_end
else:
i += 1
cnt += 1
log.info('ループ回数: %d' % cnt)
return results
def main():
| 64 | 64 | 118 | 3 | 60 | t2y/python-study | SearchString/brute_force_search.py | Python | main | main | 48 | 62 | 48 | 48 | 8314bcf4ab7b951802777593ba58f086a854965e | bigcode/the-stack | train |
10b9d0a1b6493abdccd71218 | train | function | def _google_temp_unit(units):
"""Return Google temperature unit."""
if units == TEMP_FAHRENHEIT:
return 'F'
return 'C'
| def _google_temp_unit(units):
| """Return Google temperature unit."""
if units == TEMP_FAHRENHEIT:
return 'F'
return 'C'
| ES = PREFIX_COMMANDS + 'SetModes'
COMMAND_OPENCLOSE = PREFIX_COMMANDS + 'OpenClose'
TRAITS = []
def register_trait(trait):
"""Decorate a function to register a trait."""
TRAITS.append(trait)
return trait
def _google_temp_unit(units):
| 64 | 64 | 36 | 8 | 55 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | _google_temp_unit | _google_temp_unit | 82 | 86 | 82 | 82 | 961ae5c419a1d504acc428d0c7b0ed7b01130c57 | bigcode/the-stack | train |
5136e63ae976e436473dc9c2 | train | class | @register_trait
class StartStopTrait(_Trait):
"""Trait to offer StartStop functionality.
https://developers.google.com/actions/smarthome/traits/startstop
"""
name = TRAIT_STARTSTOP
commands = [
COMMAND_STARTSTOP,
COMMAND_PAUSEUNPAUSE
]
@staticmethod
def supported(domai... | @register_trait
class StartStopTrait(_Trait):
| """Trait to offer StartStop functionality.
https://developers.google.com/actions/smarthome/traits/startstop
"""
name = TRAIT_STARTSTOP
commands = [
COMMAND_STARTSTOP,
COMMAND_PAUSEUNPAUSE
]
@staticmethod
def supported(domain, features):
"""Test if state is supp... | def sync_attributes(self):
"""Return dock attributes for a sync request."""
return {}
def query_attributes(self):
"""Return dock query attributes."""
return {'isDocked': self.state.state == vacuum.STATE_DOCKED}
async def execute(self, command, data, params):
"""Exec... | 120 | 120 | 402 | 11 | 109 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | StartStopTrait | StartStopTrait | 473 | 527 | 473 | 474 | 52acc04946dfda8e1049395ebed9d427997bafa4 | bigcode/the-stack | train |
c55368cb7bfac8a1539ba667 | train | class | @register_trait
class OpenCloseTrait(_Trait):
"""Trait to open and close a cover.
https://developers.google.com/actions/smarthome/traits/openclose
"""
name = TRAIT_OPENCLOSE
commands = [
COMMAND_OPENCLOSE
]
@staticmethod
def supported(domain, features):
"""Test if stat... | @register_trait
class OpenCloseTrait(_Trait):
| """Trait to open and close a cover.
https://developers.google.com/actions/smarthome/traits/openclose
"""
name = TRAIT_OPENCLOSE
commands = [
COMMAND_OPENCLOSE
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""
return domain == co... | def execute(self, command, data, params):
"""Execute an SetModes command."""
settings = params.get('updateModeSettings')
requested_source = settings.get(
self.HA_TO_GOOGLE.get(media_player.ATTR_INPUT_SOURCE))
if requested_source:
for src in self.state.attributes... | 152 | 152 | 508 | 11 | 141 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | OpenCloseTrait | OpenCloseTrait | 1,032 | 1,102 | 1,032 | 1,033 | 91bc5251be8b942470603c3cd6cb0a28ba6ff781 | bigcode/the-stack | train |
b7a3830a0ca87283a2ddde7d | train | class | @register_trait
class DockTrait(_Trait):
"""Trait to offer dock functionality.
https://developers.google.com/actions/smarthome/traits/dock
"""
name = TRAIT_DOCK
commands = [
COMMAND_DOCK
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""... | @register_trait
class DockTrait(_Trait):
| """Trait to offer dock functionality.
https://developers.google.com/actions/smarthome/traits/dock
"""
name = TRAIT_DOCK
commands = [
COMMAND_DOCK
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""
return domain == vacuum.DOMAIN
... | for scripts as they can be slow.
await self.hass.services.async_call(
self.state.domain, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: self.state.entity_id
}, blocking=self.state.domain != script.DOMAIN,
context=data.context)
@register_trait
class DockTrait(_Trait):
| 64 | 64 | 191 | 10 | 54 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | DockTrait | DockTrait | 440 | 470 | 440 | 441 | 9750bee1c1354a2fe79fd95de8e8b433441bb17d | bigcode/the-stack | train |
6fdfccd06f0d50a2e78a6c59 | train | class | @register_trait
class LockUnlockTrait(_Trait):
"""Trait to lock or unlock a lock.
https://developers.google.com/actions/smarthome/traits/lockunlock
"""
name = TRAIT_LOCKUNLOCK
commands = [
COMMAND_LOCKUNLOCK
]
@staticmethod
def supported(domain, features):
"""Test if s... | @register_trait
class LockUnlockTrait(_Trait):
| """Trait to lock or unlock a lock.
https://developers.google.com/actions/smarthome/traits/lockunlock
"""
name = TRAIT_LOCKUNLOCK
commands = [
COMMAND_LOCKUNLOCK
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""
return domain == ... | elif supported & climate.SUPPORT_OPERATION_MODE:
await self.hass.services.async_call(
climate.DOMAIN, climate.SERVICE_SET_OPERATION_MODE, {
ATTR_ENTITY_ID: self.state.entity_id,
climate.ATTR_OPERATION_MODE:
... | 77 | 77 | 259 | 11 | 66 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | LockUnlockTrait | LockUnlockTrait | 729 | 768 | 729 | 730 | 96f1ea22b02de5797808160a7c0b6e1b316dd4b0 | bigcode/the-stack | train |
dab212e325a6c7c07b6c6fc7 | train | class | @register_trait
class FanSpeedTrait(_Trait):
"""Trait to control speed of Fan.
https://developers.google.com/actions/smarthome/traits/fanspeed
"""
name = TRAIT_FANSPEED
commands = [
COMMAND_FANSPEED
]
speed_synonyms = {
fan.SPEED_OFF: ['stop', 'off'],
fan.SPEED_LOW... | @register_trait
class FanSpeedTrait(_Trait):
| """Trait to control speed of Fan.
https://developers.google.com/actions/smarthome/traits/fanspeed
"""
name = TRAIT_FANSPEED
commands = [
COMMAND_FANSPEED
]
speed_synonyms = {
fan.SPEED_OFF: ['stop', 'off'],
fan.SPEED_LOW: ['slow', 'low', 'slowest', 'lowest'],
... | return {'isLocked': self.state.state == STATE_LOCKED}
def can_execute(self, command, params):
"""Test if command can be executed."""
allowed_unlock = not params['lock'] and self.config.allow_unlock
return params['lock'] or allowed_unlock
async def execute(self, command, data, p... | 148 | 148 | 495 | 11 | 137 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | FanSpeedTrait | FanSpeedTrait | 771 | 844 | 771 | 772 | c515d4963825692a0ab807f554ec3ae3801271cb | bigcode/the-stack | train |
8eabe98d7a4d4ed8d3d7c012 | train | class | @register_trait
class SceneTrait(_Trait):
"""Trait to offer scene functionality.
https://developers.google.com/actions/smarthome/traits/scene
"""
name = TRAIT_SCENE
commands = [
COMMAND_ACTIVATE_SCENE
]
@staticmethod
def supported(domain, features):
"""Test if state is... | @register_trait
class SceneTrait(_Trait):
| """Trait to offer scene functionality.
https://developers.google.com/actions/smarthome/traits/scene
"""
name = TRAIT_SCENE
commands = [
COMMAND_ACTIVATE_SCENE
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""
return domain in (s... | format(min_temp,
max_temp))
await self.hass.services.async_call(light.DOMAIN, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: self.state.entity_id,
light.ATTR_COLOR_TEMP: temp,
}, blocking=True, context=data.context)
@register_... | 64 | 64 | 212 | 10 | 54 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | SceneTrait | SceneTrait | 404 | 437 | 404 | 405 | 5757604f4789dd89adad27bfed18246be9afde57 | bigcode/the-stack | train |
fd01c0bf2903593b9a75c0d3 | train | class | @register_trait
class ColorSpectrumTrait(_Trait):
"""Trait to offer color spectrum functionality.
https://developers.google.com/actions/smarthome/traits/colorspectrum
"""
name = TRAIT_COLOR_SPECTRUM
commands = [
COMMAND_COLOR_ABSOLUTE
]
@staticmethod
def supported(domain, feat... | @register_trait
class ColorSpectrumTrait(_Trait):
| """Trait to offer color spectrum functionality.
https://developers.google.com/actions/smarthome/traits/colorspectrum
"""
name = TRAIT_COLOR_SPECTRUM
commands = [
COMMAND_COLOR_ABSOLUTE
]
@staticmethod
def supported(domain, features):
"""Test if state is supported."""
... | Execute an OnOff command."""
domain = self.state.domain
if domain == group.DOMAIN:
service_domain = HA_DOMAIN
service = SERVICE_TURN_ON if params['on'] else SERVICE_TURN_OFF
else:
service_domain = domain
service = SERVICE_TURN_ON if params['on'] ... | 117 | 117 | 393 | 11 | 106 | markusressel/home-assistant | homeassistant/components/google_assistant/trait.py | Python | ColorSpectrumTrait | ColorSpectrumTrait | 275 | 328 | 275 | 276 | 49df266471d63a762510c30ca7fbe9020e1e4f65 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.