code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AccountEmailaddress', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('email', models.CharField(max_length=254, unique=True)), ('verified', models.IntegerField()), ('primary', models.IntegerField()), ], options={ 'db_table': 'account_emailaddress', 'managed': False, }, ), migrations.CreateModel( name='AccountEmailconfirmation', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('created', models.DateTimeField()), ('sent', models.DateTimeField(blank=True, null=True)), ('key', models.CharField(max_length=64, unique=True)), ], options={ 'db_table': 'account_emailconfirmation', 'managed': False, }, ), migrations.CreateModel( name='AuthGroup', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=150, unique=True)), ], options={ 'db_table': 'auth_group', 'managed': False, }, ), migrations.CreateModel( name='AuthGroupPermissions', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_group_permissions', 'managed': False, }, ), migrations.CreateModel( name='AuthPermission', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('codename', models.CharField(max_length=100)), ], options={ 'db_table': 'auth_permission', 'managed': False, }, ), migrations.CreateModel( name='AuthUser', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128)), ('last_login', models.DateTimeField(blank=True, null=True)), ('is_superuser', models.IntegerField()), ('username', models.CharField(max_length=150, unique=True)), ('first_name', models.CharField(max_length=150)), ('last_name', models.CharField(max_length=150)), ('email', models.CharField(max_length=254)), ('is_staff', models.IntegerField()), ('is_active', models.IntegerField()), ('date_joined', models.DateTimeField()), ], options={ 'db_table': 'auth_user', 'managed': False, }, ), migrations.CreateModel( name='AuthUserGroups', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_user_groups', 'managed': False, }, ), migrations.CreateModel( name='AuthUserUserPermissions', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_user_user_permissions', 'managed': False, }, ), migrations.CreateModel( name='DjangoAdminLog', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('action_time', models.DateTimeField()), ('object_id', models.TextField(blank=True, null=True)), ('object_repr', models.CharField(max_length=200)), ('action_flag', models.PositiveSmallIntegerField()), ('change_message', models.TextField()), ], options={ 'db_table': 'django_admin_log', 'managed': False, }, ), migrations.CreateModel( name='DjangoContentType', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('app_label', models.CharField(max_length=100)), ('model', models.CharField(max_length=100)), ], options={ 'db_table': 'django_content_type', 'managed': False, }, ), migrations.CreateModel( name='DjangoMigrations', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('app', models.CharField(max_length=255)), ('name', models.CharField(max_length=255)), ('applied', models.DateTimeField()), ], options={ 'db_table': 'django_migrations', 'managed': False, }, ), migrations.CreateModel( name='DjangoSession', fields=[ ('session_key', models.CharField(max_length=40, primary_key=True, serialize=False)), ('session_data', models.TextField()), ('expire_date', models.DateTimeField()), ], options={ 'db_table': 'django_session', 'managed': False, }, ), migrations.CreateModel( name='DjangoSite', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('domain', models.CharField(max_length=100, unique=True)), ('name', models.CharField(max_length=50)), ], options={ 'db_table': 'django_site', 'managed': False, }, ), migrations.CreateModel( name='GroupArticleComments', fields=[ ('commentid', models.AutoField(primary_key=True, serialize=False)), ('comment', models.CharField(max_length=100)), ('writedate', models.DateTimeField()), ('is_talkback', models.IntegerField()), ], options={ 'db_table': 'grouparticlecomments', 'managed': False, }, ), migrations.CreateModel( name='GroupArticles', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('grouparticletitle', models.CharField(max_length=64)), ('grouparticlecontent', models.CharField(max_length=150)), ('grouparticlecategory', models.SmallIntegerField(db_column='groupArticleCategory')), ('uploaddate', models.DateTimeField()), ], options={ 'db_table': 'group_articles', 'managed': False, }, ), migrations.CreateModel( name='GroupAssignments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('groupassignment', models.CharField(db_column='groupAssignment', max_length=32)), ('groupassignmentdetail', models.CharField(db_column='groupAssignmentdetail', max_length=500)), ('groupassignmentlimit', models.DateTimeField(db_column='groupAssignmentlimit')), ], options={ 'db_table': 'group_assignments', 'managed': False, }, ), migrations.CreateModel( name='GroupCalendar', fields=[ ('groupplanid', models.AutoField(db_column='groupPlanid', primary_key=True, serialize=False)), ('groupplanname', models.CharField(db_column='groupPlanname', max_length=64)), ('groupplaninfo', models.CharField(db_column='groupPlaninfo', max_length=128)), ('groupplanlink', models.CharField(blank=True, db_column='groupPlanlink', max_length=200, null=True)), ('groupplanstart', models.DateTimeField(db_column='groupPlanstart')), ('groupplanend', models.DateTimeField(db_column='groupPlanend')), ], options={ 'db_table': 'group_calendar', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialaccount', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('provider', models.CharField(max_length=30)), ('uid', models.CharField(max_length=191)), ('last_login', models.DateTimeField()), ('date_joined', models.DateTimeField()), ('extra_data', models.TextField()), ], options={ 'db_table': 'socialaccount_socialaccount', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialapp', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('provider', models.CharField(max_length=30)), ('name', models.CharField(max_length=40)), ('client_id', models.CharField(max_length=191)), ('secret', models.CharField(max_length=191)), ('key', models.CharField(max_length=191)), ], options={ 'db_table': 'socialaccount_socialapp', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialappSites', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('socialapp_id', models.BigIntegerField()), ], options={ 'db_table': 'socialaccount_socialapp_sites', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialtoken', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('token', models.TextField()), ('token_secret', models.TextField()), ('expires_at', models.DateTimeField(blank=True, null=True)), ], options={ 'db_table': 'socialaccount_socialtoken', 'managed': False, }, ), migrations.CreateModel( name='Studygroups', fields=[ ('groupid', models.AutoField(db_column='groupID', primary_key=True, serialize=False)), ('groupname', models.CharField(db_column='groupName', max_length=64)), ('grouppasscode', models.CharField(db_column='groupPasscode', max_length=64)), ], options={ 'db_table': 'studygroups', 'managed': False, }, ), migrations.CreateModel( name='UsersGroupsMapping', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'users_groups_mapping', 'managed': False, }, ), ]
whatshouldido/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AccountEmailaddress', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('email', models.CharField(max_length=254, unique=True)), ('verified', models.IntegerField()), ('primary', models.IntegerField()), ], options={ 'db_table': 'account_emailaddress', 'managed': False, }, ), migrations.CreateModel( name='AccountEmailconfirmation', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('created', models.DateTimeField()), ('sent', models.DateTimeField(blank=True, null=True)), ('key', models.CharField(max_length=64, unique=True)), ], options={ 'db_table': 'account_emailconfirmation', 'managed': False, }, ), migrations.CreateModel( name='AuthGroup', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=150, unique=True)), ], options={ 'db_table': 'auth_group', 'managed': False, }, ), migrations.CreateModel( name='AuthGroupPermissions', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_group_permissions', 'managed': False, }, ), migrations.CreateModel( name='AuthPermission', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('codename', models.CharField(max_length=100)), ], options={ 'db_table': 'auth_permission', 'managed': False, }, ), migrations.CreateModel( name='AuthUser', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128)), ('last_login', models.DateTimeField(blank=True, null=True)), ('is_superuser', models.IntegerField()), ('username', models.CharField(max_length=150, unique=True)), ('first_name', models.CharField(max_length=150)), ('last_name', models.CharField(max_length=150)), ('email', models.CharField(max_length=254)), ('is_staff', models.IntegerField()), ('is_active', models.IntegerField()), ('date_joined', models.DateTimeField()), ], options={ 'db_table': 'auth_user', 'managed': False, }, ), migrations.CreateModel( name='AuthUserGroups', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_user_groups', 'managed': False, }, ), migrations.CreateModel( name='AuthUserUserPermissions', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'auth_user_user_permissions', 'managed': False, }, ), migrations.CreateModel( name='DjangoAdminLog', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('action_time', models.DateTimeField()), ('object_id', models.TextField(blank=True, null=True)), ('object_repr', models.CharField(max_length=200)), ('action_flag', models.PositiveSmallIntegerField()), ('change_message', models.TextField()), ], options={ 'db_table': 'django_admin_log', 'managed': False, }, ), migrations.CreateModel( name='DjangoContentType', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('app_label', models.CharField(max_length=100)), ('model', models.CharField(max_length=100)), ], options={ 'db_table': 'django_content_type', 'managed': False, }, ), migrations.CreateModel( name='DjangoMigrations', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('app', models.CharField(max_length=255)), ('name', models.CharField(max_length=255)), ('applied', models.DateTimeField()), ], options={ 'db_table': 'django_migrations', 'managed': False, }, ), migrations.CreateModel( name='DjangoSession', fields=[ ('session_key', models.CharField(max_length=40, primary_key=True, serialize=False)), ('session_data', models.TextField()), ('expire_date', models.DateTimeField()), ], options={ 'db_table': 'django_session', 'managed': False, }, ), migrations.CreateModel( name='DjangoSite', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('domain', models.CharField(max_length=100, unique=True)), ('name', models.CharField(max_length=50)), ], options={ 'db_table': 'django_site', 'managed': False, }, ), migrations.CreateModel( name='GroupArticleComments', fields=[ ('commentid', models.AutoField(primary_key=True, serialize=False)), ('comment', models.CharField(max_length=100)), ('writedate', models.DateTimeField()), ('is_talkback', models.IntegerField()), ], options={ 'db_table': 'grouparticlecomments', 'managed': False, }, ), migrations.CreateModel( name='GroupArticles', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('grouparticletitle', models.CharField(max_length=64)), ('grouparticlecontent', models.CharField(max_length=150)), ('grouparticlecategory', models.SmallIntegerField(db_column='groupArticleCategory')), ('uploaddate', models.DateTimeField()), ], options={ 'db_table': 'group_articles', 'managed': False, }, ), migrations.CreateModel( name='GroupAssignments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('groupassignment', models.CharField(db_column='groupAssignment', max_length=32)), ('groupassignmentdetail', models.CharField(db_column='groupAssignmentdetail', max_length=500)), ('groupassignmentlimit', models.DateTimeField(db_column='groupAssignmentlimit')), ], options={ 'db_table': 'group_assignments', 'managed': False, }, ), migrations.CreateModel( name='GroupCalendar', fields=[ ('groupplanid', models.AutoField(db_column='groupPlanid', primary_key=True, serialize=False)), ('groupplanname', models.CharField(db_column='groupPlanname', max_length=64)), ('groupplaninfo', models.CharField(db_column='groupPlaninfo', max_length=128)), ('groupplanlink', models.CharField(blank=True, db_column='groupPlanlink', max_length=200, null=True)), ('groupplanstart', models.DateTimeField(db_column='groupPlanstart')), ('groupplanend', models.DateTimeField(db_column='groupPlanend')), ], options={ 'db_table': 'group_calendar', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialaccount', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('provider', models.CharField(max_length=30)), ('uid', models.CharField(max_length=191)), ('last_login', models.DateTimeField()), ('date_joined', models.DateTimeField()), ('extra_data', models.TextField()), ], options={ 'db_table': 'socialaccount_socialaccount', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialapp', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('provider', models.CharField(max_length=30)), ('name', models.CharField(max_length=40)), ('client_id', models.CharField(max_length=191)), ('secret', models.CharField(max_length=191)), ('key', models.CharField(max_length=191)), ], options={ 'db_table': 'socialaccount_socialapp', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialappSites', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('socialapp_id', models.BigIntegerField()), ], options={ 'db_table': 'socialaccount_socialapp_sites', 'managed': False, }, ), migrations.CreateModel( name='SocialaccountSocialtoken', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ('token', models.TextField()), ('token_secret', models.TextField()), ('expires_at', models.DateTimeField(blank=True, null=True)), ], options={ 'db_table': 'socialaccount_socialtoken', 'managed': False, }, ), migrations.CreateModel( name='Studygroups', fields=[ ('groupid', models.AutoField(db_column='groupID', primary_key=True, serialize=False)), ('groupname', models.CharField(db_column='groupName', max_length=64)), ('grouppasscode', models.CharField(db_column='groupPasscode', max_length=64)), ], options={ 'db_table': 'studygroups', 'managed': False, }, ), migrations.CreateModel( name='UsersGroupsMapping', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), ], options={ 'db_table': 'users_groups_mapping', 'managed': False, }, ), ]
0.503418
0.187486
import graphene from graphene_django.types import DjangoObjectType from rx import Observable from graphene_subscriptions.events import CREATED, UPDATED, DELETED from tests.models import SomeModel CUSTOM_EVENT = "custom_event" class SomeModelType(DjangoObjectType): class Meta: model = SomeModel class SomeModelCreatedSubscription(graphene.ObjectType): some_model_created = graphene.Field(SomeModelType) def resolve_some_model_created(root, info): return root.filter( lambda event: event.operation == CREATED and isinstance(event.instance, SomeModel) ).map(lambda event: event.instance) class SomeModelUpdatedSubscription(graphene.ObjectType): some_model_updated = graphene.Field(SomeModelType, id=graphene.ID()) def resolve_some_model_updated(root, info, id): return root.filter( lambda event: event.operation == UPDATED and isinstance(event.instance, SomeModel) and event.instance.pk == int(id) ).map(lambda event: event.instance) class SomeModelDeletedSubscription(graphene.ObjectType): some_model_deleted = graphene.Field(SomeModelType, id=graphene.ID()) def resolve_some_model_deleted(root, info, id): return root.filter( lambda event: event.operation == DELETED and isinstance(event.instance, SomeModel) and event.instance.pk == int(id) ).map(lambda event: event.instance) class CustomEventSubscription(graphene.ObjectType): custom_subscription = graphene.String() def resolve_custom_subscription(root, info): return root.filter(lambda event: event.operation == CUSTOM_EVENT).map( lambda event: event.instance ) class Subscription( CustomEventSubscription, SomeModelCreatedSubscription, SomeModelUpdatedSubscription, SomeModelDeletedSubscription, ): hello = graphene.String() def resolve_hello(root, info): return Observable.of("hello world!") class Query(graphene.ObjectType): base = graphene.String() schema = graphene.Schema(query=Query, subscription=Subscription)
tests/schema.py
import graphene from graphene_django.types import DjangoObjectType from rx import Observable from graphene_subscriptions.events import CREATED, UPDATED, DELETED from tests.models import SomeModel CUSTOM_EVENT = "custom_event" class SomeModelType(DjangoObjectType): class Meta: model = SomeModel class SomeModelCreatedSubscription(graphene.ObjectType): some_model_created = graphene.Field(SomeModelType) def resolve_some_model_created(root, info): return root.filter( lambda event: event.operation == CREATED and isinstance(event.instance, SomeModel) ).map(lambda event: event.instance) class SomeModelUpdatedSubscription(graphene.ObjectType): some_model_updated = graphene.Field(SomeModelType, id=graphene.ID()) def resolve_some_model_updated(root, info, id): return root.filter( lambda event: event.operation == UPDATED and isinstance(event.instance, SomeModel) and event.instance.pk == int(id) ).map(lambda event: event.instance) class SomeModelDeletedSubscription(graphene.ObjectType): some_model_deleted = graphene.Field(SomeModelType, id=graphene.ID()) def resolve_some_model_deleted(root, info, id): return root.filter( lambda event: event.operation == DELETED and isinstance(event.instance, SomeModel) and event.instance.pk == int(id) ).map(lambda event: event.instance) class CustomEventSubscription(graphene.ObjectType): custom_subscription = graphene.String() def resolve_custom_subscription(root, info): return root.filter(lambda event: event.operation == CUSTOM_EVENT).map( lambda event: event.instance ) class Subscription( CustomEventSubscription, SomeModelCreatedSubscription, SomeModelUpdatedSubscription, SomeModelDeletedSubscription, ): hello = graphene.String() def resolve_hello(root, info): return Observable.of("hello world!") class Query(graphene.ObjectType): base = graphene.String() schema = graphene.Schema(query=Query, subscription=Subscription)
0.620047
0.203529
from polygon.rest.models import ( MarketHoliday, MarketStatus, MarketCurrencies, MarketExchanges, ) from base import BaseTest class MarketsTest(BaseTest): def test_get_market_holidays(self): holidays = self.c.get_market_holidays() expected = [ MarketHoliday( close=None, date="2022-05-30", exchange="NYSE", name="Memorial Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-05-30", exchange="NASDAQ", name="Memorial Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-06-20", exchange="NASDAQ", name="Juneteenth", open=None, status="closed", ), MarketHoliday( close=None, date="2022-06-20", exchange="NYSE", name="Juneteenth", open=None, status="closed", ), MarketHoliday( close=None, date="2022-07-04", exchange="NYSE", name="Independence Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-07-04", exchange="NASDAQ", name="Independence Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-09-05", exchange="NYSE", name="Labor Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-09-05", exchange="NASDAQ", name="Labor Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-11-24", exchange="NYSE", name="Thanksgiving", open=None, status="closed", ), MarketHoliday( close=None, date="2022-11-24", exchange="NASDAQ", name="Thanksgiving", open=None, status="closed", ), MarketHoliday( close="2022-11-25T18:00:00.000Z", date="2022-11-25", exchange="NYSE", name="Thanksgiving", open="2022-11-25T14:30:00.000Z", status="early-close", ), MarketHoliday( close="2022-11-25T18:00:00.000Z", date="2022-11-25", exchange="NASDAQ", name="Thanksgiving", open="2022-11-25T14:30:00.000Z", status="early-close", ), MarketHoliday( close=None, date="2022-12-26", exchange="NYSE", name="Christmas", open=None, status="closed", ), MarketHoliday( close=None, date="2022-12-26", exchange="NASDAQ", name="Christmas", open=None, status="closed", ), ] self.assertEqual(holidays, expected) def test_get_market_status(self): status = self.c.get_market_status() expected = MarketStatus( after_hours=True, currencies=MarketCurrencies(crypto="open", fx="open"), early_hours=False, exchanges=MarketExchanges( nasdaq="extended-hours", nyse="extended-hours", otc="extended-hours" ), market="extended-hours", server_time="2022-04-28T16:48:08-04:00", ) self.assertEqual(status, expected)
test_rest/test_markets.py
from polygon.rest.models import ( MarketHoliday, MarketStatus, MarketCurrencies, MarketExchanges, ) from base import BaseTest class MarketsTest(BaseTest): def test_get_market_holidays(self): holidays = self.c.get_market_holidays() expected = [ MarketHoliday( close=None, date="2022-05-30", exchange="NYSE", name="Memorial Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-05-30", exchange="NASDAQ", name="Memorial Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-06-20", exchange="NASDAQ", name="Juneteenth", open=None, status="closed", ), MarketHoliday( close=None, date="2022-06-20", exchange="NYSE", name="Juneteenth", open=None, status="closed", ), MarketHoliday( close=None, date="2022-07-04", exchange="NYSE", name="Independence Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-07-04", exchange="NASDAQ", name="Independence Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-09-05", exchange="NYSE", name="Labor Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-09-05", exchange="NASDAQ", name="Labor Day", open=None, status="closed", ), MarketHoliday( close=None, date="2022-11-24", exchange="NYSE", name="Thanksgiving", open=None, status="closed", ), MarketHoliday( close=None, date="2022-11-24", exchange="NASDAQ", name="Thanksgiving", open=None, status="closed", ), MarketHoliday( close="2022-11-25T18:00:00.000Z", date="2022-11-25", exchange="NYSE", name="Thanksgiving", open="2022-11-25T14:30:00.000Z", status="early-close", ), MarketHoliday( close="2022-11-25T18:00:00.000Z", date="2022-11-25", exchange="NASDAQ", name="Thanksgiving", open="2022-11-25T14:30:00.000Z", status="early-close", ), MarketHoliday( close=None, date="2022-12-26", exchange="NYSE", name="Christmas", open=None, status="closed", ), MarketHoliday( close=None, date="2022-12-26", exchange="NASDAQ", name="Christmas", open=None, status="closed", ), ] self.assertEqual(holidays, expected) def test_get_market_status(self): status = self.c.get_market_status() expected = MarketStatus( after_hours=True, currencies=MarketCurrencies(crypto="open", fx="open"), early_hours=False, exchanges=MarketExchanges( nasdaq="extended-hours", nyse="extended-hours", otc="extended-hours" ), market="extended-hours", server_time="2022-04-28T16:48:08-04:00", ) self.assertEqual(status, expected)
0.691706
0.305795
from unittest import TestCase, main from project.student import Student class TestStudent(TestCase): def setUp(self): self.student = Student("Ivan") self.student_with_course = Student("Ivan", {"math": ["some notes"]}) def test_initializing(self): self.assertEqual("Ivan", self.student.name) self.assertEqual({}, self.student.courses) self.assertEqual({"math": ["some notes"]}, self.student_with_course.courses) def test_course_already_in(self): result = self.student_with_course.enroll("math", ["more notes"]) self.assertEqual("Course already added. Notes have been updated.", result) expected_notes = ["some notes", "more notes"] actual_notes = self.student_with_course.courses['math'] self.assertEqual(expected_notes, actual_notes) def test_add_course_notes(self): result1 = self.student_with_course.enroll("physics", ["new notes"], "Y") result2 = self.student_with_course.enroll("biology", ["new notes"]) self.assertEqual("Course and course notes have been added.", result1) self.assertEqual("Course and course notes have been added.", result2) self.assertEqual(["new notes"], self.student_with_course.courses["physics"]) self.assertEqual(["new notes"], self.student_with_course.courses["biology"]) def test_without_adding_notes(self): result = self.student.enroll("math", "", "no notes") self.assertEqual("Course has been added.", result) self.assertEqual([], self.student.courses["math"]) def test_add_notes_on_existing_course(self): result = self.student_with_course.add_notes("math", "a+b=c") self.assertEqual("Notes have been updated", result) self.assertEqual(["some notes", "a+b=c"], self.student_with_course.courses["math"]) def test_add_notes_to_non_existing_course(self): with self.assertRaises(Exception) as ex: self.student.add_notes("math", "a+b=c") self.assertEqual("Cannot add notes. Course not found.", str(ex.exception)) def test_leaving_existing_course(self): result = self.student_with_course.leave_course("math") self.assertEqual("Course has been removed", result) with self.assertRaises(KeyError): result = self.student_with_course.courses["math"] def test_leaving_non_existing_course(self): with self.assertRaises(Exception) as ex: self.student.leave_course("math") self.assertEqual("Cannot remove course. Course not found.", str(ex.exception)) if __name__ == '__main__': main()
Testing - Exercise/test/test_student.py
from unittest import TestCase, main from project.student import Student class TestStudent(TestCase): def setUp(self): self.student = Student("Ivan") self.student_with_course = Student("Ivan", {"math": ["some notes"]}) def test_initializing(self): self.assertEqual("Ivan", self.student.name) self.assertEqual({}, self.student.courses) self.assertEqual({"math": ["some notes"]}, self.student_with_course.courses) def test_course_already_in(self): result = self.student_with_course.enroll("math", ["more notes"]) self.assertEqual("Course already added. Notes have been updated.", result) expected_notes = ["some notes", "more notes"] actual_notes = self.student_with_course.courses['math'] self.assertEqual(expected_notes, actual_notes) def test_add_course_notes(self): result1 = self.student_with_course.enroll("physics", ["new notes"], "Y") result2 = self.student_with_course.enroll("biology", ["new notes"]) self.assertEqual("Course and course notes have been added.", result1) self.assertEqual("Course and course notes have been added.", result2) self.assertEqual(["new notes"], self.student_with_course.courses["physics"]) self.assertEqual(["new notes"], self.student_with_course.courses["biology"]) def test_without_adding_notes(self): result = self.student.enroll("math", "", "no notes") self.assertEqual("Course has been added.", result) self.assertEqual([], self.student.courses["math"]) def test_add_notes_on_existing_course(self): result = self.student_with_course.add_notes("math", "a+b=c") self.assertEqual("Notes have been updated", result) self.assertEqual(["some notes", "a+b=c"], self.student_with_course.courses["math"]) def test_add_notes_to_non_existing_course(self): with self.assertRaises(Exception) as ex: self.student.add_notes("math", "a+b=c") self.assertEqual("Cannot add notes. Course not found.", str(ex.exception)) def test_leaving_existing_course(self): result = self.student_with_course.leave_course("math") self.assertEqual("Course has been removed", result) with self.assertRaises(KeyError): result = self.student_with_course.courses["math"] def test_leaving_non_existing_course(self): with self.assertRaises(Exception) as ex: self.student.leave_course("math") self.assertEqual("Cannot remove course. Course not found.", str(ex.exception)) if __name__ == '__main__': main()
0.695028
0.627152
__author__ = "TetrisFinalBoss" __version__ = "0.4.3" import sys import cv2 import numpy import pafy import re import os.path import getopt AGS_DS2_PLAYLIST = 'PL_ftpUY_ldBTtHOUQLt5irghX1XfIzoy-' def getFile(media): for stream in media.streams: if stream.dimensions[1] == 360 and stream.extension=='mp4': m = re.search('\[Part\s?([\d]+)(\s-\sFinal)?\]',media.title) fname = "%s - %s.%s"%(m.group(1),media.videoid,stream.extension) if not os.path.isfile(fname): print 'Downloading video %s from playlist'%(m.group(1)) stream.download(fname) else: print "File '%s' already exists, skipping download"%(fname) return fname def tsum(t1,t2): return tuple(map(lambda x,y: x + y,t1,t2)) class DialogLocator: D_MATCHMINIMUM = 0.5 D_WINDOW = {'left':396, 'top':61, 'right':418, 'bottom':84} def __init__(self): self.__dialogPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/dialog_pattern.png",cv2.IMREAD_GRAYSCALE) def locate(self, img): res = cv2.matchTemplate(img[self.D_WINDOW['top']:self.D_WINDOW['bottom'],self.D_WINDOW['left']:self.D_WINDOW['right']], self.__dialogPattern, cv2.TM_SQDIFF_NORMED) min_val = cv2.minMaxLoc(res)[0] if min_val>self.D_MATCHMINIMUM: return False return True class SomethingExplainedDetector: MATCHMINIMUM = 0.4 QUOT_WINDOW = {'left':20, 'top':15, 'right':50, 'bottom':42} EXPL_WINDOW = {'left':20, 'top':15, 'right':400, 'bottom':42} def __init__(self): self.__count = 0 self.__ncount = 0 self.__quotPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/quot_pattern.png",cv2.IMREAD_GRAYSCALE) self.__explPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/expl_pattern.png",cv2.IMREAD_GRAYSCALE) self.__quotDim = self.__quotPattern.shape self.__explDim = self.__explPattern.shape def detect(self, img): ret = [] # Search for patterns, first quotation mark res = cv2.matchTemplate(img[self.QUOT_WINDOW['top']:self.QUOT_WINDOW['bottom'], self.QUOT_WINDOW['left']:self.QUOT_WINDOW['right']], self.__quotPattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.QUOT_WINDOW['left'],self.QUOT_WINDOW['top'])) bottom_right = tsum(top_left, (self.__quotDim[1],self.__quotDim[0])) ret.append((top_left,bottom_right)) else: # No new objects, but __count stays the same until dialog is over self.__ncount = 0 return ret # Second 'explained' word res = cv2.matchTemplate(img[self.EXPL_WINDOW['top']:self.EXPL_WINDOW['bottom'], self.EXPL_WINDOW['left']:self.EXPL_WINDOW['right']], self.__explPattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.EXPL_WINDOW['left'],self.EXPL_WINDOW['top'])) bottom_right = tsum(top_left, (self.__explDim[1],self.__explDim[0])) ret.append((top_left,bottom_right)) else: # No new objects, but __count stays the same until dialog is over self.__ncount = 0 return ret # Both are found, mess with counters self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 return ret def reset(self): self.__count = 0 self.__ncount = 0 def dialogClosed(self): # If no dialog arrow is found reset all values self.__ncount = 0 self.__count = 0 def name(self): return "'someone explained something'" def uniqueObjects(self): return False def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class CircumstancesExplainedDetector: MATCHMINIMUM = 0.4 SEARCH_WINDOW = {'left':10, 'top':10, 'right':400, 'bottom':84} def __init__(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] self.__ec1Pattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/etc_pattern.png",cv2.IMREAD_GRAYSCALE) self.__ec1Dim = self.__ec1Pattern.shape def detect(self, img): ret = self.__pobj # Search for pattern res = cv2.matchTemplate(img[self.SEARCH_WINDOW['top']:self.SEARCH_WINDOW['bottom'], self.SEARCH_WINDOW['left']:self.SEARCH_WINDOW['right']], self.__ec1Pattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.SEARCH_WINDOW['left'],self.SEARCH_WINDOW['top'])) bottom_right = tsum(top_left, (self.__ec1Dim[1],self.__ec1Dim[0])) ret = [(top_left,bottom_right)] self.__pobj = ret self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 else: # Nothing is found, but if we've already found something in this dialog box # let's assume that this object is still present, because this detector is blocking one self.__count = len(self.__pobj) self.__ncount = 0 return ret def reset(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def dialogClosed(self): # If no dialog arrow is found reset all values self.__ncount = 0 self.__count = 0 self.__pobj = [] def name(self): return "'explained the circumstances'" def uniqueObjects(self): return True def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class MeaningfulSilenceDetector: MATCHMINIMUM = 0.4 PATTERN_SIZE = (16,60,1) PATTERN_OFFSET = {'x':18,'y':10} SEARCH_WINDOW = {'left':10, 'top':10, 'right':110, 'bottom':40} PATTERN_COLOR = 127 def __init__(self): self.__pattern = numpy.zeros(self.PATTERN_SIZE, numpy.uint8) for i in xrange(6): cv2.rectangle(self.__pattern, (self.PATTERN_OFFSET['x']+7*i,self.PATTERN_OFFSET['y']), (self.PATTERN_OFFSET['x']+1+7*i,self.PATTERN_OFFSET['y']+1), self.PATTERN_COLOR, -1) self.__count = 0 self.__ncount = 0 self.__pobj = [] def detect(self, img): # Set "default" return value to previously found object in this dialog entry # which is reset to [] when dialog is closed ret = self.__pobj # Search for pattern res = cv2.matchTemplate(img[self.SEARCH_WINDOW['top']:self.SEARCH_WINDOW['bottom'], self.SEARCH_WINDOW['left']:self.SEARCH_WINDOW['right']], self.__pattern, cv2.TM_SQDIFF_NORMED) # There can be only one "......" in dialog, so we totally fine with global minimum min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if min_val < self.MATCHMINIMUM: top_left = tsum(min_loc, (self.SEARCH_WINDOW['left'],self.SEARCH_WINDOW['top'])) bottom_right = tsum(top_left, (self.PATTERN_SIZE[1],self.PATTERN_SIZE[0])) # Something is found, set return value and store this object for future use ret = [(top_left,bottom_right)] self.__pobj = ret self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 else: # Nothing is found, but if we've already found something in this dialog box # let's assume that this object is still present self.__count = len(self.__pobj) self.__ncount = 0 return ret def dialogClosed(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def reset(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def name(self): return "'......'" def uniqueObjects(self): return True def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class MidSentenceEllipsesDetector: MATCHMINIMUM = 0.5 PATTERN_SIZE = (8,20,1) PATTERN_OFFSET = {'x':1,'y':3} PATTERN_COLOR = 127 def __init__(self): self.__pattern = numpy.zeros(self.PATTERN_SIZE, numpy.uint8) for i in xrange(3): cv2.rectangle(self.__pattern, (self.PATTERN_OFFSET['x']+7*i,self.PATTERN_OFFSET['y']), (self.PATTERN_OFFSET['x']+1+7*i,self.PATTERN_OFFSET['y']+1), self.PATTERN_COLOR, -1) self.__ncount = 0 self.__count = 0 def detect(self, img): ret = [] res = cv2.matchTemplate(img,self.__pattern,cv2.TM_SQDIFF_NORMED) # For each row in dialog do recursive search for global minimums def localMinInRow(row,offset): # Current dimensions h,w = row.shape min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(row) if min_val < self.MATCHMINIMUM: x,y = min_loc # Recalculate absolute position and append value min_loc = tsum(min_loc,offset) ret.append((min_loc,tsum(min_loc, (self.PATTERN_SIZE[1],self.PATTERN_SIZE[0])))) # Add threshold around this point mthresh = self.PATTERN_SIZE[1] # Now search minimums in left region if x-mthresh>self.PATTERN_SIZE[1]: localMinInRow(row[0:h,0:x-mthresh],offset) # And in right region if w-x-mthresh > self.PATTERN_SIZE[1]: localMinInRow(row[0:h,x+mthresh:w],tsum(offset,(x+mthresh,0))) for i in xrange(3): yoff = 20+i*20+4 localMinInRow(res[yoff:yoff+18,20:400],(20,yoff)) # Sometimes objects may be lost and caught again later # Let's try to address this issue l = len(ret) # Get new objects count self.__ncount = l - self.__count if self.__ncount<0: self.__ncount = 0 # Store object count, but assuming, that objects can't disappear # during same dialog line, so it alway stays at maximum level self.__count = max(l,self.__count) return ret def reset(self): self.__ncount = 0 self.__count = 0 def dialogClosed(self): self.__ncount = 0 self.__count = 0 def name(self): return "'...'" def uniqueObjects(self): return False def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class EllipsesSearcher: # Threshold values THRESHOLD_VALUE = 90 THRESHOLD_COLOR = 127 # Dialog box window DIALOG = {'left':104,'top':248,'right':538,'bottom':340} # Dialog box highlight DIALOG_HIGHLIGHT = {'lt': (1,1), 'br': (432, 90)} def __init__(self): # Init detectors self.__detectors = [] self.__detectors.append(MeaningfulSilenceDetector()) self.__detectors.append(MidSentenceEllipsesDetector()) self.__detectors.append(CircumstancesExplainedDetector()) self.__detectors.append(SomethingExplainedDetector()) # Init dialog locator self.__dialogLocator = DialogLocator() # Reset other values self.__total = len(self.__detectors)*[0] self.__frames = len(self.__detectors)*[0] self.snapshots = False self.statFile = None self.useStatFile = False self.ignoreStat = False self.preview = False self.detectorMask = 0xff def __thresh(self,img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, t = cv2.threshold(gray, self.THRESHOLD_VALUE, self.THRESHOLD_COLOR, cv2.THRESH_TOZERO) return t def __writeUserStatObject(self, det, m, s): if self.useStatFile: self.statFile.write("%s is found at %s:%s\n"%(det,m,s)) self.statFile.flush() def __writeUserStatHeader(self, fname): if self.useStatFile: self.statFile.write("===\n%s\n===\n"%(fname)) self.statFile.flush() def __writeUserStatTotal(self, lst): if self.useStatFile: self.statFile.write("===\n") for e in lst: self.statFile.write("%s is said %d times (%d frames)\n"%e) self.statFile.write("\n") self.statFile.flush() def __readStat(self,fname): if self.ignoreStat: return False try: statfile = open('statistics/'+fname+'.stat','r') count = len(self.__detectors)*[0] frames = len(self.__detectors)*[0] for ln in statfile.readlines(): m = re.search('OBJECT\s([\d]+)\s([\d]+):([\d]+)',ln) if m: # Last parameter is object type - i.e. detector number det = int(m.group(1)) self.__writeUserStatObject(self.__detectors[det].name(),m.group(2),m.group(3)) # And increase counter count[det]+=1 continue m = re.search('FRAMES\s([\d]+)\s([\d]+)',ln) if m: frames[int(m.group(1))]+=int(m.group(2)) continue statfile.close() # Increase total value self.__total = map(lambda x,y: x+y, count, self.__total) self.__frames = map(lambda x,y: x+y, frames, self.__frames) # Display progress print "Reading statistics from file: Done - %d objects detected"%(sum(count)) # And also write to user specified file self.__writeUserStatTotal(zip(map(lambda x: x.name(), self.__detectors), count, frames)) # And that's it, this file is done return True except (OSError, IOError): return False def count(self,fname): self.__writeUserStatHeader(fname) # First - try to get statistics from file, # so we don't have to recalculate stats once again if self.__readStat(fname): return count = len(self.__detectors)*[0] frames = len(self.__detectors)*[0] # Reset detectors before apply them to new file for d in self.__detectors: d.reset() statfile = open('statistics/'+fname+'.stat','w') v = cv2.VideoCapture(fname) frame_count = int(v.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) frame_no = 0 previewRate = 1 while v.isOpened(): ret, frame = v.read() frame_no+=1 if not ret: break # Use simple threshold for dialog box box = frame[self.DIALOG['top']:self.DIALOG['bottom'],self.DIALOG['left']:self.DIALOG['right']] t = self.__thresh(box) objects = [] shouldSaveSnapshot = False secs = int(v.get(cv2.cv.CV_CAP_PROP_POS_MSEC)/1000) dialogClosed = not self.__dialogLocator.locate(t) # Now apply all detectors for this frame for i in xrange(len(self.__detectors)): # Check if detector is enabled if (self.detectorMask & (1 << i)) == 0: continue if dialogClosed: self.__detectors[i].dialogClosed() continue # Apply detector to thresholded picture and store all found objects for this particular detector items = self.__detectors[i].detect(t) # If some of these objects are new ncount = self.__detectors[i].newObjectsCount() if ncount>0: count[i] += ncount self.__total[i] += ncount shouldSaveSnapshot = self.snapshots for j in xrange(ncount): # Write to user specified file self.__writeUserStatObject(self.__detectors[i].name(),secs/60,secs%60) # And store stats for future use statfile.write('OBJECT %d %d:%d\n'%(i,secs/60,secs%60)) if len(items): objects += items # We check stored objects count value for detector instead len(items) # This way detectors can return objects just for preview without possible effect on statistics if self.__detectors[i].objectsCount()>0: # First of all - increase frame counter for that object frames[i] += 1 self.__frames[i] += 1 # If we found unique object (i.e. there can't be any other objects in this picture) - stop applying detectors if self.__detectors[i].uniqueObjects(): break # Prepare images if shouldSaveSnapshot or self.preview: for item in objects: if shouldSaveSnapshot: cv2.rectangle(box,item[0],item[1],(0xff,0,0)) if self.preview: cv2.rectangle(t,item[0],item[1],0xff) # Save snapshot if shouldSaveSnapshot: cv2.imwrite("snapshots/%s.%d-%d.png"%(fname,secs/60,secs%60),box) # Show preview window if enabled if self.preview: if not dialogClosed: cv2.rectangle(t, self.DIALOG_HIGHLIGHT['lt'], self.DIALOG_HIGHLIGHT['br'], 0xff) cv2.imshow("Picture",t) k = cv2.waitKey(previewRate) & 0xff if k==ord('q'): sys.exit(0) elif k==ord('s'): cv2.imwrite('snapshots/snapshot_orig.png',box) cv2.imwrite('snapshots/snapshot_modified.png',t) elif k==ord('n'): previewRate = 0 elif k==ord('p'): previewRate = 1 # Display some progress progress = frame_no*100/frame_count sys.stdout.write("Processing video: %d%% - %d objects found\r"%(progress, sum(count))) sys.stdout.flush() # Display final state for this file print "Processing video: Done - %d objects found"%(sum(count)) # And also write to user specified file self.__writeUserStatTotal(zip(map(lambda x: x.name(), self.__detectors), count, frames)) # And save frame statistics for e in enumerate(frames): statfile.write('FRAMES %d %d\n'%e) v.release() statfile.close() def total(self): ret = "" for e in zip(map(lambda x: x.name(), self.__detectors), self.__total, self.__frames): ret = ret+"%s is said %d times (%d frames)\n"%e return ret if __name__=="__main__": el = EllipsesSearcher() downloadOnly = False try: opts, args = getopt.getopt(sys.argv[1:],"hirdvf:m:") except getopt.GetoptError as err: print str(err) sys.exit(1) for opt, arg in opts: if opt == '-h': print 'Usage: %s [-h] [-i] [-r] [-d] [-v] [-f filename] [-m mask]'%(sys.argv[0]) print '-h -- Show this help' print '-i -- Save snapshots each time ellipses is found' print '-r -- Ignore (reset) previously collected statistics' print '-d -- Download only' print '-v -- Display video preview (debug mode)' print '-m <mask> -- Set detector mask to <mask>' print '-f <file> -- Write statistics to <file>' sys.exit() elif opt == "-i": print 'Snapshots is enabled' if not os.path.isdir('snapshots'): os.mkdir('snapshots') el.snapshots = True elif opt == "-r": el.ignoreStat = True elif opt == "-v": el.preview = True elif opt == "-d": downloadOnly = True elif opt == "-f": el.useStatFile = True el.statFile = open(arg,'w') elif opt == "-m": el.detectorMask = int(arg) if not os.path.isdir('statistics'): os.mkdir('statistics') # get Devil Summoner 2 playlist playList = pafy.get_playlist(AGS_DS2_PLAYLIST) for media in playList['items']: fname = getFile(media['pafy']) if not downloadOnly: el.count(fname) print "We are done!" if downloadOnly: print "Playlist downloaded!" else: print el.total() if el.useStatFile: el.statFile.write("===\nTotal\n===\n%s"%(el.total())) el.statFile.flush()
ags-ds2.py
__author__ = "TetrisFinalBoss" __version__ = "0.4.3" import sys import cv2 import numpy import pafy import re import os.path import getopt AGS_DS2_PLAYLIST = 'PL_ftpUY_ldBTtHOUQLt5irghX1XfIzoy-' def getFile(media): for stream in media.streams: if stream.dimensions[1] == 360 and stream.extension=='mp4': m = re.search('\[Part\s?([\d]+)(\s-\sFinal)?\]',media.title) fname = "%s - %s.%s"%(m.group(1),media.videoid,stream.extension) if not os.path.isfile(fname): print 'Downloading video %s from playlist'%(m.group(1)) stream.download(fname) else: print "File '%s' already exists, skipping download"%(fname) return fname def tsum(t1,t2): return tuple(map(lambda x,y: x + y,t1,t2)) class DialogLocator: D_MATCHMINIMUM = 0.5 D_WINDOW = {'left':396, 'top':61, 'right':418, 'bottom':84} def __init__(self): self.__dialogPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/dialog_pattern.png",cv2.IMREAD_GRAYSCALE) def locate(self, img): res = cv2.matchTemplate(img[self.D_WINDOW['top']:self.D_WINDOW['bottom'],self.D_WINDOW['left']:self.D_WINDOW['right']], self.__dialogPattern, cv2.TM_SQDIFF_NORMED) min_val = cv2.minMaxLoc(res)[0] if min_val>self.D_MATCHMINIMUM: return False return True class SomethingExplainedDetector: MATCHMINIMUM = 0.4 QUOT_WINDOW = {'left':20, 'top':15, 'right':50, 'bottom':42} EXPL_WINDOW = {'left':20, 'top':15, 'right':400, 'bottom':42} def __init__(self): self.__count = 0 self.__ncount = 0 self.__quotPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/quot_pattern.png",cv2.IMREAD_GRAYSCALE) self.__explPattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/expl_pattern.png",cv2.IMREAD_GRAYSCALE) self.__quotDim = self.__quotPattern.shape self.__explDim = self.__explPattern.shape def detect(self, img): ret = [] # Search for patterns, first quotation mark res = cv2.matchTemplate(img[self.QUOT_WINDOW['top']:self.QUOT_WINDOW['bottom'], self.QUOT_WINDOW['left']:self.QUOT_WINDOW['right']], self.__quotPattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.QUOT_WINDOW['left'],self.QUOT_WINDOW['top'])) bottom_right = tsum(top_left, (self.__quotDim[1],self.__quotDim[0])) ret.append((top_left,bottom_right)) else: # No new objects, but __count stays the same until dialog is over self.__ncount = 0 return ret # Second 'explained' word res = cv2.matchTemplate(img[self.EXPL_WINDOW['top']:self.EXPL_WINDOW['bottom'], self.EXPL_WINDOW['left']:self.EXPL_WINDOW['right']], self.__explPattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.EXPL_WINDOW['left'],self.EXPL_WINDOW['top'])) bottom_right = tsum(top_left, (self.__explDim[1],self.__explDim[0])) ret.append((top_left,bottom_right)) else: # No new objects, but __count stays the same until dialog is over self.__ncount = 0 return ret # Both are found, mess with counters self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 return ret def reset(self): self.__count = 0 self.__ncount = 0 def dialogClosed(self): # If no dialog arrow is found reset all values self.__ncount = 0 self.__count = 0 def name(self): return "'someone explained something'" def uniqueObjects(self): return False def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class CircumstancesExplainedDetector: MATCHMINIMUM = 0.4 SEARCH_WINDOW = {'left':10, 'top':10, 'right':400, 'bottom':84} def __init__(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] self.__ec1Pattern = cv2.imread(os.path.dirname(sys.argv[0]) + "/etc_pattern.png",cv2.IMREAD_GRAYSCALE) self.__ec1Dim = self.__ec1Pattern.shape def detect(self, img): ret = self.__pobj # Search for pattern res = cv2.matchTemplate(img[self.SEARCH_WINDOW['top']:self.SEARCH_WINDOW['bottom'], self.SEARCH_WINDOW['left']:self.SEARCH_WINDOW['right']], self.__ec1Pattern, cv2.TM_SQDIFF_NORMED) minmax = cv2.minMaxLoc(res) if minmax[0] < self.MATCHMINIMUM: top_left = tsum(minmax[2], (self.SEARCH_WINDOW['left'],self.SEARCH_WINDOW['top'])) bottom_right = tsum(top_left, (self.__ec1Dim[1],self.__ec1Dim[0])) ret = [(top_left,bottom_right)] self.__pobj = ret self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 else: # Nothing is found, but if we've already found something in this dialog box # let's assume that this object is still present, because this detector is blocking one self.__count = len(self.__pobj) self.__ncount = 0 return ret def reset(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def dialogClosed(self): # If no dialog arrow is found reset all values self.__ncount = 0 self.__count = 0 self.__pobj = [] def name(self): return "'explained the circumstances'" def uniqueObjects(self): return True def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class MeaningfulSilenceDetector: MATCHMINIMUM = 0.4 PATTERN_SIZE = (16,60,1) PATTERN_OFFSET = {'x':18,'y':10} SEARCH_WINDOW = {'left':10, 'top':10, 'right':110, 'bottom':40} PATTERN_COLOR = 127 def __init__(self): self.__pattern = numpy.zeros(self.PATTERN_SIZE, numpy.uint8) for i in xrange(6): cv2.rectangle(self.__pattern, (self.PATTERN_OFFSET['x']+7*i,self.PATTERN_OFFSET['y']), (self.PATTERN_OFFSET['x']+1+7*i,self.PATTERN_OFFSET['y']+1), self.PATTERN_COLOR, -1) self.__count = 0 self.__ncount = 0 self.__pobj = [] def detect(self, img): # Set "default" return value to previously found object in this dialog entry # which is reset to [] when dialog is closed ret = self.__pobj # Search for pattern res = cv2.matchTemplate(img[self.SEARCH_WINDOW['top']:self.SEARCH_WINDOW['bottom'], self.SEARCH_WINDOW['left']:self.SEARCH_WINDOW['right']], self.__pattern, cv2.TM_SQDIFF_NORMED) # There can be only one "......" in dialog, so we totally fine with global minimum min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if min_val < self.MATCHMINIMUM: top_left = tsum(min_loc, (self.SEARCH_WINDOW['left'],self.SEARCH_WINDOW['top'])) bottom_right = tsum(top_left, (self.PATTERN_SIZE[1],self.PATTERN_SIZE[0])) # Something is found, set return value and store this object for future use ret = [(top_left,bottom_right)] self.__pobj = ret self.__ncount = self.__count==0 and 1 or 0 self.__count = 1 else: # Nothing is found, but if we've already found something in this dialog box # let's assume that this object is still present self.__count = len(self.__pobj) self.__ncount = 0 return ret def dialogClosed(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def reset(self): self.__count = 0 self.__ncount = 0 self.__pobj = [] def name(self): return "'......'" def uniqueObjects(self): return True def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class MidSentenceEllipsesDetector: MATCHMINIMUM = 0.5 PATTERN_SIZE = (8,20,1) PATTERN_OFFSET = {'x':1,'y':3} PATTERN_COLOR = 127 def __init__(self): self.__pattern = numpy.zeros(self.PATTERN_SIZE, numpy.uint8) for i in xrange(3): cv2.rectangle(self.__pattern, (self.PATTERN_OFFSET['x']+7*i,self.PATTERN_OFFSET['y']), (self.PATTERN_OFFSET['x']+1+7*i,self.PATTERN_OFFSET['y']+1), self.PATTERN_COLOR, -1) self.__ncount = 0 self.__count = 0 def detect(self, img): ret = [] res = cv2.matchTemplate(img,self.__pattern,cv2.TM_SQDIFF_NORMED) # For each row in dialog do recursive search for global minimums def localMinInRow(row,offset): # Current dimensions h,w = row.shape min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(row) if min_val < self.MATCHMINIMUM: x,y = min_loc # Recalculate absolute position and append value min_loc = tsum(min_loc,offset) ret.append((min_loc,tsum(min_loc, (self.PATTERN_SIZE[1],self.PATTERN_SIZE[0])))) # Add threshold around this point mthresh = self.PATTERN_SIZE[1] # Now search minimums in left region if x-mthresh>self.PATTERN_SIZE[1]: localMinInRow(row[0:h,0:x-mthresh],offset) # And in right region if w-x-mthresh > self.PATTERN_SIZE[1]: localMinInRow(row[0:h,x+mthresh:w],tsum(offset,(x+mthresh,0))) for i in xrange(3): yoff = 20+i*20+4 localMinInRow(res[yoff:yoff+18,20:400],(20,yoff)) # Sometimes objects may be lost and caught again later # Let's try to address this issue l = len(ret) # Get new objects count self.__ncount = l - self.__count if self.__ncount<0: self.__ncount = 0 # Store object count, but assuming, that objects can't disappear # during same dialog line, so it alway stays at maximum level self.__count = max(l,self.__count) return ret def reset(self): self.__ncount = 0 self.__count = 0 def dialogClosed(self): self.__ncount = 0 self.__count = 0 def name(self): return "'...'" def uniqueObjects(self): return False def objectsCount(self): return self.__count def newObjectsCount(self): return self.__ncount class EllipsesSearcher: # Threshold values THRESHOLD_VALUE = 90 THRESHOLD_COLOR = 127 # Dialog box window DIALOG = {'left':104,'top':248,'right':538,'bottom':340} # Dialog box highlight DIALOG_HIGHLIGHT = {'lt': (1,1), 'br': (432, 90)} def __init__(self): # Init detectors self.__detectors = [] self.__detectors.append(MeaningfulSilenceDetector()) self.__detectors.append(MidSentenceEllipsesDetector()) self.__detectors.append(CircumstancesExplainedDetector()) self.__detectors.append(SomethingExplainedDetector()) # Init dialog locator self.__dialogLocator = DialogLocator() # Reset other values self.__total = len(self.__detectors)*[0] self.__frames = len(self.__detectors)*[0] self.snapshots = False self.statFile = None self.useStatFile = False self.ignoreStat = False self.preview = False self.detectorMask = 0xff def __thresh(self,img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, t = cv2.threshold(gray, self.THRESHOLD_VALUE, self.THRESHOLD_COLOR, cv2.THRESH_TOZERO) return t def __writeUserStatObject(self, det, m, s): if self.useStatFile: self.statFile.write("%s is found at %s:%s\n"%(det,m,s)) self.statFile.flush() def __writeUserStatHeader(self, fname): if self.useStatFile: self.statFile.write("===\n%s\n===\n"%(fname)) self.statFile.flush() def __writeUserStatTotal(self, lst): if self.useStatFile: self.statFile.write("===\n") for e in lst: self.statFile.write("%s is said %d times (%d frames)\n"%e) self.statFile.write("\n") self.statFile.flush() def __readStat(self,fname): if self.ignoreStat: return False try: statfile = open('statistics/'+fname+'.stat','r') count = len(self.__detectors)*[0] frames = len(self.__detectors)*[0] for ln in statfile.readlines(): m = re.search('OBJECT\s([\d]+)\s([\d]+):([\d]+)',ln) if m: # Last parameter is object type - i.e. detector number det = int(m.group(1)) self.__writeUserStatObject(self.__detectors[det].name(),m.group(2),m.group(3)) # And increase counter count[det]+=1 continue m = re.search('FRAMES\s([\d]+)\s([\d]+)',ln) if m: frames[int(m.group(1))]+=int(m.group(2)) continue statfile.close() # Increase total value self.__total = map(lambda x,y: x+y, count, self.__total) self.__frames = map(lambda x,y: x+y, frames, self.__frames) # Display progress print "Reading statistics from file: Done - %d objects detected"%(sum(count)) # And also write to user specified file self.__writeUserStatTotal(zip(map(lambda x: x.name(), self.__detectors), count, frames)) # And that's it, this file is done return True except (OSError, IOError): return False def count(self,fname): self.__writeUserStatHeader(fname) # First - try to get statistics from file, # so we don't have to recalculate stats once again if self.__readStat(fname): return count = len(self.__detectors)*[0] frames = len(self.__detectors)*[0] # Reset detectors before apply them to new file for d in self.__detectors: d.reset() statfile = open('statistics/'+fname+'.stat','w') v = cv2.VideoCapture(fname) frame_count = int(v.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) frame_no = 0 previewRate = 1 while v.isOpened(): ret, frame = v.read() frame_no+=1 if not ret: break # Use simple threshold for dialog box box = frame[self.DIALOG['top']:self.DIALOG['bottom'],self.DIALOG['left']:self.DIALOG['right']] t = self.__thresh(box) objects = [] shouldSaveSnapshot = False secs = int(v.get(cv2.cv.CV_CAP_PROP_POS_MSEC)/1000) dialogClosed = not self.__dialogLocator.locate(t) # Now apply all detectors for this frame for i in xrange(len(self.__detectors)): # Check if detector is enabled if (self.detectorMask & (1 << i)) == 0: continue if dialogClosed: self.__detectors[i].dialogClosed() continue # Apply detector to thresholded picture and store all found objects for this particular detector items = self.__detectors[i].detect(t) # If some of these objects are new ncount = self.__detectors[i].newObjectsCount() if ncount>0: count[i] += ncount self.__total[i] += ncount shouldSaveSnapshot = self.snapshots for j in xrange(ncount): # Write to user specified file self.__writeUserStatObject(self.__detectors[i].name(),secs/60,secs%60) # And store stats for future use statfile.write('OBJECT %d %d:%d\n'%(i,secs/60,secs%60)) if len(items): objects += items # We check stored objects count value for detector instead len(items) # This way detectors can return objects just for preview without possible effect on statistics if self.__detectors[i].objectsCount()>0: # First of all - increase frame counter for that object frames[i] += 1 self.__frames[i] += 1 # If we found unique object (i.e. there can't be any other objects in this picture) - stop applying detectors if self.__detectors[i].uniqueObjects(): break # Prepare images if shouldSaveSnapshot or self.preview: for item in objects: if shouldSaveSnapshot: cv2.rectangle(box,item[0],item[1],(0xff,0,0)) if self.preview: cv2.rectangle(t,item[0],item[1],0xff) # Save snapshot if shouldSaveSnapshot: cv2.imwrite("snapshots/%s.%d-%d.png"%(fname,secs/60,secs%60),box) # Show preview window if enabled if self.preview: if not dialogClosed: cv2.rectangle(t, self.DIALOG_HIGHLIGHT['lt'], self.DIALOG_HIGHLIGHT['br'], 0xff) cv2.imshow("Picture",t) k = cv2.waitKey(previewRate) & 0xff if k==ord('q'): sys.exit(0) elif k==ord('s'): cv2.imwrite('snapshots/snapshot_orig.png',box) cv2.imwrite('snapshots/snapshot_modified.png',t) elif k==ord('n'): previewRate = 0 elif k==ord('p'): previewRate = 1 # Display some progress progress = frame_no*100/frame_count sys.stdout.write("Processing video: %d%% - %d objects found\r"%(progress, sum(count))) sys.stdout.flush() # Display final state for this file print "Processing video: Done - %d objects found"%(sum(count)) # And also write to user specified file self.__writeUserStatTotal(zip(map(lambda x: x.name(), self.__detectors), count, frames)) # And save frame statistics for e in enumerate(frames): statfile.write('FRAMES %d %d\n'%e) v.release() statfile.close() def total(self): ret = "" for e in zip(map(lambda x: x.name(), self.__detectors), self.__total, self.__frames): ret = ret+"%s is said %d times (%d frames)\n"%e return ret if __name__=="__main__": el = EllipsesSearcher() downloadOnly = False try: opts, args = getopt.getopt(sys.argv[1:],"hirdvf:m:") except getopt.GetoptError as err: print str(err) sys.exit(1) for opt, arg in opts: if opt == '-h': print 'Usage: %s [-h] [-i] [-r] [-d] [-v] [-f filename] [-m mask]'%(sys.argv[0]) print '-h -- Show this help' print '-i -- Save snapshots each time ellipses is found' print '-r -- Ignore (reset) previously collected statistics' print '-d -- Download only' print '-v -- Display video preview (debug mode)' print '-m <mask> -- Set detector mask to <mask>' print '-f <file> -- Write statistics to <file>' sys.exit() elif opt == "-i": print 'Snapshots is enabled' if not os.path.isdir('snapshots'): os.mkdir('snapshots') el.snapshots = True elif opt == "-r": el.ignoreStat = True elif opt == "-v": el.preview = True elif opt == "-d": downloadOnly = True elif opt == "-f": el.useStatFile = True el.statFile = open(arg,'w') elif opt == "-m": el.detectorMask = int(arg) if not os.path.isdir('statistics'): os.mkdir('statistics') # get Devil Summoner 2 playlist playList = pafy.get_playlist(AGS_DS2_PLAYLIST) for media in playList['items']: fname = getFile(media['pafy']) if not downloadOnly: el.count(fname) print "We are done!" if downloadOnly: print "Playlist downloaded!" else: print el.total() if el.useStatFile: el.statFile.write("===\nTotal\n===\n%s"%(el.total())) el.statFile.flush()
0.278944
0.109372
import logging import jwt import requests from jwt import PyJWKClient from users_microservice.cfg import config from users_microservice.constants import ( DEFAULT_AUDIENCE, DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY, DEFAULT_GOOGLE_OPENID_CFG_URI, ) from users_microservice.exceptions import EmailAlreadyRegistered from users_microservice.models import User, db from users_microservice.utils import split_list logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def validated_token(token, verify=True): """Validate a token and return decoded token.""" url = ( requests.get( config.oauth.google_openid_config_uri(default=DEFAULT_GOOGLE_OPENID_CFG_URI) ) .json() .get( config.oauth.google_openid_jkws_key( default=DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY ) ) ) logger.info("JWK url is %s", url) jwks_client = PyJWKClient(url) signing_key = jwks_client.get_signing_key_from_jwt(token) data = jwt.decode( token, signing_key.key, algorithms=["RS256"], audience=config.oauth.audience(default=DEFAULT_AUDIENCE, cast=split_list), options={"verify_signature": verify}, ) return data def oauth_user(token): """Get user from token.""" decoded_token = validated_token(token, False) user = User.query.filter(User.email == decoded_token["email"]).first() return user def create_oauth_user(token, wallet_address, wallet_mnemonic): """Create a new user from OAuth token.""" if oauth_user(token) is not None: raise EmailAlreadyRegistered data = validated_token(token) new_user_data = { "first_name": data["given_name"], "last_name": data["family_name"], "password": data["sub"], "profile_picture": data["picture"], "wallet_address": wallet_address, "wallet_mnemonic": wallet_mnemonic, "email": data["email"], } new_user = User(**new_user_data) db.session.add(new_user) db.session.commit() return new_user
users_microservice/controllers/oauth.py
import logging import jwt import requests from jwt import PyJWKClient from users_microservice.cfg import config from users_microservice.constants import ( DEFAULT_AUDIENCE, DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY, DEFAULT_GOOGLE_OPENID_CFG_URI, ) from users_microservice.exceptions import EmailAlreadyRegistered from users_microservice.models import User, db from users_microservice.utils import split_list logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def validated_token(token, verify=True): """Validate a token and return decoded token.""" url = ( requests.get( config.oauth.google_openid_config_uri(default=DEFAULT_GOOGLE_OPENID_CFG_URI) ) .json() .get( config.oauth.google_openid_jkws_key( default=DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY ) ) ) logger.info("JWK url is %s", url) jwks_client = PyJWKClient(url) signing_key = jwks_client.get_signing_key_from_jwt(token) data = jwt.decode( token, signing_key.key, algorithms=["RS256"], audience=config.oauth.audience(default=DEFAULT_AUDIENCE, cast=split_list), options={"verify_signature": verify}, ) return data def oauth_user(token): """Get user from token.""" decoded_token = validated_token(token, False) user = User.query.filter(User.email == decoded_token["email"]).first() return user def create_oauth_user(token, wallet_address, wallet_mnemonic): """Create a new user from OAuth token.""" if oauth_user(token) is not None: raise EmailAlreadyRegistered data = validated_token(token) new_user_data = { "first_name": data["given_name"], "last_name": data["family_name"], "password": data["sub"], "profile_picture": data["picture"], "wallet_address": wallet_address, "wallet_mnemonic": wallet_mnemonic, "email": data["email"], } new_user = User(**new_user_data) db.session.add(new_user) db.session.commit() return new_user
0.563858
0.152347
import base64 import traceback from Crypto.Cipher import AES from .type_tool import TypeTool from .b64 import Base64 def pkcs7padding(data): bs = AES.block_size padding = bs - len(data) % bs padding_text = chr(padding) * padding return data + padding_text.encode() def pkcs7unpadding(data): lengt = len(data) unpadding = data[lengt - 1] if type(data[lengt - 1]) is int else ord(data[lengt - 1]) return data[0:lengt - unpadding] class Aes: """ AES加密 """ def __init__(self, key: str = "_ZhangDapeng520%"): self.key = key.encode() def encrypt(self, data): """ AES 加密, 加密模式ECB,填充:pkcs7padding,密钥长度:256 :param data: :return: """ data = pkcs7padding(data) cipher = AES.new(self.key, AES.MODE_ECB) encrypted = cipher.encrypt(data) return base64.b64encode(encrypted) def decrypt(self, data): """ AES解密 :param data: 要解密的数据 :return: 解密后的数据 """ data = base64.b64decode(data) cipher = AES.new(self.key, AES.MODE_ECB) decrypted = cipher.decrypt(data) decrypted = pkcs7unpadding(decrypted) return decrypted.decode() @classmethod @TypeTool.type_assert def encrypt_gcm(cls, cdata: [str, bytes, bytearray], key: [str, bytes, bytearray]) -> [tuple]: """ AES加密 :param cdata: 要加密的数据 :param key: 加密的key :return: """ error_return = (bytes(), bytes(), bytes()) try: # 将参数转换为字节数组 cdata = TypeTool.type_sbb_2_bytes(cdata) key = TypeTool.type_sbb_2_bytes(key) # 校验参数的长度 if len(key) != 16: return error_return # 创建cipher对象 aescipher = AES.new(key, AES.MODE_GCM) # 加密 edata, tag = aescipher.encrypt_and_digest(cdata) # 获取nonce nonce = aescipher.nonce # 返回加密结果 return edata, nonce, tag except Exception as e: print(e) traceback.print_exc() # 返回错误结果 return error_return @classmethod def encrypt_gcm_str(cls, cdata: str, key: str) -> (str, str, str): """ AES加密字符串 :param cdata: 要加密的数据 :param key: 加密的key :return: 加密后的数据base6编码字符串 """ # 加密 edata, nonce, tag = cls.encrypt_gcm(cdata.encode(), key.encode()) # 转换为base64编码 edata_b64 = Base64.encode_str(edata) nonce_b64 = Base64.encode_str(nonce) tag_b64 = Base64.encode_str(tag) # 返回base64编码 return edata_b64, nonce_b64, tag_b64 @classmethod @TypeTool.type_assert def decrypt_gcm(cls, edata: [str, bytes, bytearray], key: [str, bytes, bytearray], nonce: [str, bytes, bytearray], tag: [str, bytes, bytearray]) -> [bytes]: """ AES解密 :param edata: 要解密的数据 :param key: 解密的key :param nonce: 解密的nonce :param tag: 解密的标签 :return: 解密后的数据 """ error_return = bytes() try: # 将参数都转换为字节数组 edata = TypeTool.type_sbb_2_bytes(edata) key = TypeTool.type_sbb_2_bytes(key) nonce = TypeTool.type_sbb_2_bytes(nonce) tag = TypeTool.type_sbb_2_bytes(tag) # 判断参数的长度 if (len(key) != 16) or (len(nonce) != 16) or (len(tag) != 16): return error_return # 创建cipher aescipher = AES.new(key, AES.MODE_GCM, nonce) # 数据解密并校验 cdata = aescipher.decrypt_and_verify(edata, tag) # 返回解密后的数据 return cdata except Exception as e: print(e) traceback.print_exc() return error_return @classmethod def decrypt_gcm_str(cls, edata: str, key: str, nonce: str, tag: str) -> str: """ 解密字符串 :param edata: 要解密的数据 :param key: 解密的key :param nonce: 解密的nonce :param tag: 解密的tag :return: 解密后的字符串 """ # 将参数转换为字节数组 edata_bytes = Base64.decode(edata) key_bytes = key.encode() nonce_bytes = Base64.decode(nonce) tag_bytes = Base64.decode(tag) # 解密 result_bytes = cls.decrypt_gcm(edata_bytes, key_bytes, nonce_bytes, tag_bytes) # 将解密结果解码 return result_bytes.decode('utf-8')
zdppy_password/aes.py
import base64 import traceback from Crypto.Cipher import AES from .type_tool import TypeTool from .b64 import Base64 def pkcs7padding(data): bs = AES.block_size padding = bs - len(data) % bs padding_text = chr(padding) * padding return data + padding_text.encode() def pkcs7unpadding(data): lengt = len(data) unpadding = data[lengt - 1] if type(data[lengt - 1]) is int else ord(data[lengt - 1]) return data[0:lengt - unpadding] class Aes: """ AES加密 """ def __init__(self, key: str = "_ZhangDapeng520%"): self.key = key.encode() def encrypt(self, data): """ AES 加密, 加密模式ECB,填充:pkcs7padding,密钥长度:256 :param data: :return: """ data = pkcs7padding(data) cipher = AES.new(self.key, AES.MODE_ECB) encrypted = cipher.encrypt(data) return base64.b64encode(encrypted) def decrypt(self, data): """ AES解密 :param data: 要解密的数据 :return: 解密后的数据 """ data = base64.b64decode(data) cipher = AES.new(self.key, AES.MODE_ECB) decrypted = cipher.decrypt(data) decrypted = pkcs7unpadding(decrypted) return decrypted.decode() @classmethod @TypeTool.type_assert def encrypt_gcm(cls, cdata: [str, bytes, bytearray], key: [str, bytes, bytearray]) -> [tuple]: """ AES加密 :param cdata: 要加密的数据 :param key: 加密的key :return: """ error_return = (bytes(), bytes(), bytes()) try: # 将参数转换为字节数组 cdata = TypeTool.type_sbb_2_bytes(cdata) key = TypeTool.type_sbb_2_bytes(key) # 校验参数的长度 if len(key) != 16: return error_return # 创建cipher对象 aescipher = AES.new(key, AES.MODE_GCM) # 加密 edata, tag = aescipher.encrypt_and_digest(cdata) # 获取nonce nonce = aescipher.nonce # 返回加密结果 return edata, nonce, tag except Exception as e: print(e) traceback.print_exc() # 返回错误结果 return error_return @classmethod def encrypt_gcm_str(cls, cdata: str, key: str) -> (str, str, str): """ AES加密字符串 :param cdata: 要加密的数据 :param key: 加密的key :return: 加密后的数据base6编码字符串 """ # 加密 edata, nonce, tag = cls.encrypt_gcm(cdata.encode(), key.encode()) # 转换为base64编码 edata_b64 = Base64.encode_str(edata) nonce_b64 = Base64.encode_str(nonce) tag_b64 = Base64.encode_str(tag) # 返回base64编码 return edata_b64, nonce_b64, tag_b64 @classmethod @TypeTool.type_assert def decrypt_gcm(cls, edata: [str, bytes, bytearray], key: [str, bytes, bytearray], nonce: [str, bytes, bytearray], tag: [str, bytes, bytearray]) -> [bytes]: """ AES解密 :param edata: 要解密的数据 :param key: 解密的key :param nonce: 解密的nonce :param tag: 解密的标签 :return: 解密后的数据 """ error_return = bytes() try: # 将参数都转换为字节数组 edata = TypeTool.type_sbb_2_bytes(edata) key = TypeTool.type_sbb_2_bytes(key) nonce = TypeTool.type_sbb_2_bytes(nonce) tag = TypeTool.type_sbb_2_bytes(tag) # 判断参数的长度 if (len(key) != 16) or (len(nonce) != 16) or (len(tag) != 16): return error_return # 创建cipher aescipher = AES.new(key, AES.MODE_GCM, nonce) # 数据解密并校验 cdata = aescipher.decrypt_and_verify(edata, tag) # 返回解密后的数据 return cdata except Exception as e: print(e) traceback.print_exc() return error_return @classmethod def decrypt_gcm_str(cls, edata: str, key: str, nonce: str, tag: str) -> str: """ 解密字符串 :param edata: 要解密的数据 :param key: 解密的key :param nonce: 解密的nonce :param tag: 解密的tag :return: 解密后的字符串 """ # 将参数转换为字节数组 edata_bytes = Base64.decode(edata) key_bytes = key.encode() nonce_bytes = Base64.decode(nonce) tag_bytes = Base64.decode(tag) # 解密 result_bytes = cls.decrypt_gcm(edata_bytes, key_bytes, nonce_bytes, tag_bytes) # 将解密结果解码 return result_bytes.decode('utf-8')
0.491944
0.403684
import unittest import numpy as np from .. import qxrf from ...utils import units from ...patch import jsonpickle class test_qxrf(unittest.TestCase): def geometryinstance(self): energy = 10 geometryinstance = qxrf.factory("sxm1", simplecalibration=False) info = { "I0_counts": 300, "It_counts": 30, "time": 1, "dark": True, "gaindiodeI0": 1e8, "gaindiodeIt": 1e7, } geometryinstance.calibrate_diodes(**info) info["I0_counts"] = 10000 info["It_counts"] = 100000 info["energy"] = energy - 2 info["dark"] = False geometryinstance.calibrate_diodes(**info) info["I0_counts"] = 5000 info["energy"] = energy + 2 geometryinstance.calibrate_diodes(**info) geometryinstance.reference = units.Quantity(1e9, "Hz") geometryinstance.defaultexpotime = units.Quantity(100, "ms") return geometryinstance @unittest.skipIf( qxrf.xrfdetectors.compoundfromname.xraylib is None, "xraylib not installed" ) def test_flux(self): geometryinstance = self.geometryinstance() energy = 10 time = 0.2 refflux = 1e9 flux = np.linspace(1e9, 1e8, 20) # ph/sec iodet = geometryinstance.fluxtocps(energy, flux) * time flux2 = geometryinstance.responsetoflux(energy, iodet / time) np.testing.assert_allclose(flux, flux2) # Normalize data to the real flux (use flux reference) rates = np.random.poisson(np.full_like(flux, 100)) # 1/ph/sec data = flux * time * rates # measured xrf # measured when flux whould have been refflux at each poi1e9 dataref = refflux * time * rates ref = units.Quantity(refflux, "hertz") op, _, _, _ = geometryinstance.xrfnormop(energy, expotime=time, reference=ref) np.testing.assert_allclose(dataref, data / op(iodet)) # Normalize data to the real flux (use iodet reference) iodetref = geometryinstance.fluxtocps(energy, refflux) * time ref = units.Quantity(iodetref, "dimensionless") op, _, _, _ = geometryinstance.xrfnormop(energy, expotime=time, reference=ref) np.testing.assert_allclose(dataref, data / op(iodet)) @unittest.skipIf( qxrf.xrfgeometries.compoundfromname.xraylib is None, "xraylib not installed" ) def test_serialize(self): xrfgeometries = [] for detectorposition in [0, 1]: geometry = { "name": "sxm120", "parameters": {"detectorposition": detectorposition}, } detector = {"name": "leia", "parameters": {}} xrfgeometries.append((geometry, detector)) g1 = qxrf.factory("sxm1", xrfgeometries=xrfgeometries) g2 = jsonpickle.loads(jsonpickle.dumps(g1)) self.assertEqual(g1, g2) exclude = ("QXRFGeometry",) for name, cls in qxrf.QXRFGeometry.clsregistry.items(): if name not in exclude: g1 = cls() g2 = jsonpickle.loads(jsonpickle.dumps(g1)) self.assertEqual(g1, g2) def test_suite(): """Test suite including all test suites""" testSuite = unittest.TestSuite() testSuite.addTest(test_qxrf("test_flux")) testSuite.addTest(test_qxrf("test_serialize")) return testSuite if __name__ == "__main__": import sys mysuite = test_suite() runner = unittest.TextTestRunner() if not runner.run(mysuite).wasSuccessful(): sys.exit(1)
spectrocrunch/geometries/tests/test_qxrf.py
import unittest import numpy as np from .. import qxrf from ...utils import units from ...patch import jsonpickle class test_qxrf(unittest.TestCase): def geometryinstance(self): energy = 10 geometryinstance = qxrf.factory("sxm1", simplecalibration=False) info = { "I0_counts": 300, "It_counts": 30, "time": 1, "dark": True, "gaindiodeI0": 1e8, "gaindiodeIt": 1e7, } geometryinstance.calibrate_diodes(**info) info["I0_counts"] = 10000 info["It_counts"] = 100000 info["energy"] = energy - 2 info["dark"] = False geometryinstance.calibrate_diodes(**info) info["I0_counts"] = 5000 info["energy"] = energy + 2 geometryinstance.calibrate_diodes(**info) geometryinstance.reference = units.Quantity(1e9, "Hz") geometryinstance.defaultexpotime = units.Quantity(100, "ms") return geometryinstance @unittest.skipIf( qxrf.xrfdetectors.compoundfromname.xraylib is None, "xraylib not installed" ) def test_flux(self): geometryinstance = self.geometryinstance() energy = 10 time = 0.2 refflux = 1e9 flux = np.linspace(1e9, 1e8, 20) # ph/sec iodet = geometryinstance.fluxtocps(energy, flux) * time flux2 = geometryinstance.responsetoflux(energy, iodet / time) np.testing.assert_allclose(flux, flux2) # Normalize data to the real flux (use flux reference) rates = np.random.poisson(np.full_like(flux, 100)) # 1/ph/sec data = flux * time * rates # measured xrf # measured when flux whould have been refflux at each poi1e9 dataref = refflux * time * rates ref = units.Quantity(refflux, "hertz") op, _, _, _ = geometryinstance.xrfnormop(energy, expotime=time, reference=ref) np.testing.assert_allclose(dataref, data / op(iodet)) # Normalize data to the real flux (use iodet reference) iodetref = geometryinstance.fluxtocps(energy, refflux) * time ref = units.Quantity(iodetref, "dimensionless") op, _, _, _ = geometryinstance.xrfnormop(energy, expotime=time, reference=ref) np.testing.assert_allclose(dataref, data / op(iodet)) @unittest.skipIf( qxrf.xrfgeometries.compoundfromname.xraylib is None, "xraylib not installed" ) def test_serialize(self): xrfgeometries = [] for detectorposition in [0, 1]: geometry = { "name": "sxm120", "parameters": {"detectorposition": detectorposition}, } detector = {"name": "leia", "parameters": {}} xrfgeometries.append((geometry, detector)) g1 = qxrf.factory("sxm1", xrfgeometries=xrfgeometries) g2 = jsonpickle.loads(jsonpickle.dumps(g1)) self.assertEqual(g1, g2) exclude = ("QXRFGeometry",) for name, cls in qxrf.QXRFGeometry.clsregistry.items(): if name not in exclude: g1 = cls() g2 = jsonpickle.loads(jsonpickle.dumps(g1)) self.assertEqual(g1, g2) def test_suite(): """Test suite including all test suites""" testSuite = unittest.TestSuite() testSuite.addTest(test_qxrf("test_flux")) testSuite.addTest(test_qxrf("test_serialize")) return testSuite if __name__ == "__main__": import sys mysuite = test_suite() runner = unittest.TextTestRunner() if not runner.run(mysuite).wasSuccessful(): sys.exit(1)
0.674158
0.55266
import os import cv2 import glob import tqdm import argparse from lh_tool.Iterator import SingleProcess, MultiProcess import lh_tool.imageio as iio def images2video(image_path, video_file, postfix, fourcc, fps, frameSize=None): image_file_list = glob.glob(os.path.join(image_path, f'*.{postfix}')) if len(image_file_list) == 0: return video_file = os.path.abspath(image_path) + '.mp4' if video_file is None else video_file if frameSize is None: image = iio.imread(image_file_list[0]) frameSize = (image.shape[1], image.shape[0]) frameSize = tuple(frameSize) videoWriter = cv2.VideoWriter(video_file, fourcc, fps, frameSize) assert videoWriter.isOpened(), f'Failed to create file: {video_file}' for image_file in tqdm.tqdm(image_file_list, desc=video_file): image = iio.imread(image_file) if frameSize != (image.shape[1], image.shape[0]): image = cv2.resize(image, tuple(frameSize)) videoWriter.write(image) videoWriter.release() def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='.', help='path of image files') parser.add_argument('-o', '--output', type=str, help='output video file') parser.add_argument('-p', '--postfix', type=str, default='png', help='postfix of image filename') parser.add_argument('-f', '--fps', type=float, default=29.97, help='desired fps for video') parser.add_argument('-s', '--size', type=int, nargs=2, help='desired frame size for video') parser.add_argument('-r', '--recursive', action='store_true', help='convert video to images recursively') parser.add_argument('-n', '--nprocs', type=int, default=1, help='number of process') opts = parser.parse_args() print(opts) try: image_path = opts.input video_file = opts.output postfix = opts.postfix fps = opts.fps size = opts.size recursive = opts.recursive nprocs = opts.nprocs fourcc = cv2.VideoWriter.fourcc('m', 'p', '4', 'v') if recursive: image_path_list = glob.glob(os.path.join(opts.input, '*/')) if nprocs == 1: iterator = SingleProcess(images2video) else: iterator = MultiProcess(images2video, nprocs=nprocs) iterator.run(image_path_list, None, postfix, fourcc, fps, size) else: images2video(image_path, video_file, postfix, fourcc, fps, size) except AssertionError as e: print(e) if __name__ == '__main__': main()
src/lh_tool/image2video.py
import os import cv2 import glob import tqdm import argparse from lh_tool.Iterator import SingleProcess, MultiProcess import lh_tool.imageio as iio def images2video(image_path, video_file, postfix, fourcc, fps, frameSize=None): image_file_list = glob.glob(os.path.join(image_path, f'*.{postfix}')) if len(image_file_list) == 0: return video_file = os.path.abspath(image_path) + '.mp4' if video_file is None else video_file if frameSize is None: image = iio.imread(image_file_list[0]) frameSize = (image.shape[1], image.shape[0]) frameSize = tuple(frameSize) videoWriter = cv2.VideoWriter(video_file, fourcc, fps, frameSize) assert videoWriter.isOpened(), f'Failed to create file: {video_file}' for image_file in tqdm.tqdm(image_file_list, desc=video_file): image = iio.imread(image_file) if frameSize != (image.shape[1], image.shape[0]): image = cv2.resize(image, tuple(frameSize)) videoWriter.write(image) videoWriter.release() def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='.', help='path of image files') parser.add_argument('-o', '--output', type=str, help='output video file') parser.add_argument('-p', '--postfix', type=str, default='png', help='postfix of image filename') parser.add_argument('-f', '--fps', type=float, default=29.97, help='desired fps for video') parser.add_argument('-s', '--size', type=int, nargs=2, help='desired frame size for video') parser.add_argument('-r', '--recursive', action='store_true', help='convert video to images recursively') parser.add_argument('-n', '--nprocs', type=int, default=1, help='number of process') opts = parser.parse_args() print(opts) try: image_path = opts.input video_file = opts.output postfix = opts.postfix fps = opts.fps size = opts.size recursive = opts.recursive nprocs = opts.nprocs fourcc = cv2.VideoWriter.fourcc('m', 'p', '4', 'v') if recursive: image_path_list = glob.glob(os.path.join(opts.input, '*/')) if nprocs == 1: iterator = SingleProcess(images2video) else: iterator = MultiProcess(images2video, nprocs=nprocs) iterator.run(image_path_list, None, postfix, fourcc, fps, size) else: images2video(image_path, video_file, postfix, fourcc, fps, size) except AssertionError as e: print(e) if __name__ == '__main__': main()
0.283285
0.136349
import numpy as np import scipy.constants def signal_delay(st1, st2, ecef): '''Signal delay due to speed of light between station-1 to ecef position to station-2 ''' r1 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0) r2 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0) dt = (r1 + r2)/scipy.constants.c return dt def instantaneous_to_coherrent(gain, groups, N_IPP, IPP_scale=1.0, units = 'dB'): '''Using pulse encoding schema, subgroup setup and coherent integration setup; convert from instantaneous gain to coherently integrated gain. :param float gain: Instantaneous gain, linear units or in dB. :param int groups: Number of subgroups from witch signals are coherently combined, assumes subgroups are identical. :param int N_IPP: Number of pulses to coherently integrate. :param float IPP_scale: Scale the IPP effective length in case e.g. the IPP is the same but the actual TX length is lowered. :param str units: If string equals 'dB', assume input and output units should be dB, else use linear scale. :return float: Gain after coherent integration, linear units or in dB. ''' if units == 'dB': return gain + 10.0*np.log10( groups*N_IPP*IPP_scale ) else: return gain*(groups*N_IPP*IPP_scale) def coherrent_to_instantaneous(gain,groups,N_IPP,IPP_scale=1.0,units = 'dB'): '''Using pulse encoding schema, subgroup setup and coherent integration setup; convert from coherently integrated gain to instantaneous gain. :param float gain: Coherently integrated gain, linear units or in dB. :param int groups: Number of subgroups from witch signals are coherently combined, assumes subgroups are identical. :param int N_IPP: Number of pulses to coherently integrate. :param float IPP_scale: Scale the IPP effective length in case e.g. the IPP is the same but the actual TX length is lowered. :param str units: If string equals 'dB', assume input and output units should be dB, else use linear scale. :return float: Instantaneous gain, linear units or in dB. ''' if units == 'dB': return gain - 10.0*np.log10( groups*N_IPP*IPP_scale ) else: return gain/(groups*N_IPP*IPP_scale)
sorts/functions.py
import numpy as np import scipy.constants def signal_delay(st1, st2, ecef): '''Signal delay due to speed of light between station-1 to ecef position to station-2 ''' r1 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0) r2 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0) dt = (r1 + r2)/scipy.constants.c return dt def instantaneous_to_coherrent(gain, groups, N_IPP, IPP_scale=1.0, units = 'dB'): '''Using pulse encoding schema, subgroup setup and coherent integration setup; convert from instantaneous gain to coherently integrated gain. :param float gain: Instantaneous gain, linear units or in dB. :param int groups: Number of subgroups from witch signals are coherently combined, assumes subgroups are identical. :param int N_IPP: Number of pulses to coherently integrate. :param float IPP_scale: Scale the IPP effective length in case e.g. the IPP is the same but the actual TX length is lowered. :param str units: If string equals 'dB', assume input and output units should be dB, else use linear scale. :return float: Gain after coherent integration, linear units or in dB. ''' if units == 'dB': return gain + 10.0*np.log10( groups*N_IPP*IPP_scale ) else: return gain*(groups*N_IPP*IPP_scale) def coherrent_to_instantaneous(gain,groups,N_IPP,IPP_scale=1.0,units = 'dB'): '''Using pulse encoding schema, subgroup setup and coherent integration setup; convert from coherently integrated gain to instantaneous gain. :param float gain: Coherently integrated gain, linear units or in dB. :param int groups: Number of subgroups from witch signals are coherently combined, assumes subgroups are identical. :param int N_IPP: Number of pulses to coherently integrate. :param float IPP_scale: Scale the IPP effective length in case e.g. the IPP is the same but the actual TX length is lowered. :param str units: If string equals 'dB', assume input and output units should be dB, else use linear scale. :return float: Instantaneous gain, linear units or in dB. ''' if units == 'dB': return gain - 10.0*np.log10( groups*N_IPP*IPP_scale ) else: return gain/(groups*N_IPP*IPP_scale)
0.763572
0.550607
import os import subprocess from clams import arg, Command from unb_cli.project import is_project_root pip = Command( name='pip', title='pip interface and tools', description='pip interface and tools', ) @pip.register('install') @arg('package', nargs='?', default='requirements.txt') @arg('--nocache', action='store_true', help="Don't use pip's cache (fetch all packages from server).") @arg('-v', '--verbose', action='store_true', help="Enable verbose output.") def install(package, nocache, verbose): """Install package or packages from a requirements file. If `package` ends with `.txt` then `pip install -r package` is used. If `package` is not supplied, it defaults to `requirements.txt`. """ if package.endswith('.txt'): command = ['pip', 'install', '-r', package] if not verbose: command = command + ['-q'] # Find the file! It might not be in the current directory. while True: path = os.getcwd() if os.path.exists(package): print 'Installing packages from %s' % os.path.join(path, package) subprocess.call(command) break if is_project_root(path) or path == os.path.abspath(os.sep): print "%s not found in project." % package break os.chdir(os.pardir) else: subprocess.call(['pip', 'install', package]) @pip.register('install-local') def install_local(): """Install a Python egg locally (usually during development).""" subprocess.call(['pip', 'install', '-e', '.']) @pip.register('uninstall') @arg('package') def uninstall(package): """Uninstall a package using pip.""" subprocess.call(['pip', 'uninstall', package]) @pip.register('build') def build(): """Build a Python egg.""" subprocess.call(['python', 'setup.py', 'sdist', 'bdist_wheel']) @pip.register('upload') @arg('dist', help=("Package version (example: `0.0.3`). `*` will be appended " "to upload all versions (source dist and a wheel, for " "example).")) @arg('repo', help=("Repository to upload to. Common ones include, `pypi` and " "`testpypi` (they are defined in your `~/.pypirc`).")) def upload(dist, repo): """Upload a pre-built Python package. Requires [twine](https://pypi.python.org/pypi/twine). """ # TODO(nick): `cd $PROJECT_ROOT` first. dist_version = 'dist/' + '*' + dist + '*' twine_command = ['twine', 'upload', dist_version, '-r', repo] subprocess.call(twine_command)
unb_cli/unb/pip.py
import os import subprocess from clams import arg, Command from unb_cli.project import is_project_root pip = Command( name='pip', title='pip interface and tools', description='pip interface and tools', ) @pip.register('install') @arg('package', nargs='?', default='requirements.txt') @arg('--nocache', action='store_true', help="Don't use pip's cache (fetch all packages from server).") @arg('-v', '--verbose', action='store_true', help="Enable verbose output.") def install(package, nocache, verbose): """Install package or packages from a requirements file. If `package` ends with `.txt` then `pip install -r package` is used. If `package` is not supplied, it defaults to `requirements.txt`. """ if package.endswith('.txt'): command = ['pip', 'install', '-r', package] if not verbose: command = command + ['-q'] # Find the file! It might not be in the current directory. while True: path = os.getcwd() if os.path.exists(package): print 'Installing packages from %s' % os.path.join(path, package) subprocess.call(command) break if is_project_root(path) or path == os.path.abspath(os.sep): print "%s not found in project." % package break os.chdir(os.pardir) else: subprocess.call(['pip', 'install', package]) @pip.register('install-local') def install_local(): """Install a Python egg locally (usually during development).""" subprocess.call(['pip', 'install', '-e', '.']) @pip.register('uninstall') @arg('package') def uninstall(package): """Uninstall a package using pip.""" subprocess.call(['pip', 'uninstall', package]) @pip.register('build') def build(): """Build a Python egg.""" subprocess.call(['python', 'setup.py', 'sdist', 'bdist_wheel']) @pip.register('upload') @arg('dist', help=("Package version (example: `0.0.3`). `*` will be appended " "to upload all versions (source dist and a wheel, for " "example).")) @arg('repo', help=("Repository to upload to. Common ones include, `pypi` and " "`testpypi` (they are defined in your `~/.pypirc`).")) def upload(dist, repo): """Upload a pre-built Python package. Requires [twine](https://pypi.python.org/pypi/twine). """ # TODO(nick): `cd $PROJECT_ROOT` first. dist_version = 'dist/' + '*' + dist + '*' twine_command = ['twine', 'upload', dist_version, '-r', repo] subprocess.call(twine_command)
0.474144
0.110807
import torch from torch.utils.data import SubsetRandomSampler import numpy as np from Precipitation_Forecasting.precipitation_dataset import precipitation_maps_oversampled_h5 from Precipitation_Forecasting.precipitation_lightning import AA_TransUnet_base class Precip_regression_base(TransUnet_base): def __init__(self, hparams): super(Precip_regression_base, self).__init__(hparams=hparams) self.train_dataset = None self.valid_dataset = None self.train_sampler = None self.valid_sampler = None def prepare_data(self): train_transform = None valid_transform = None if self.hparams['use_oversampled_dataset']: self.train_dataset = precipitation_maps_oversampled_h5( in_file=self.hparams['dataset_folder'], num_input_images=self.hparams['num_input_images'], num_output_images=self.hparams['num_output_images'], train=True, transform=train_transform ) self.valid_dataset = precipitation_maps_oversampled_h5( in_file=self.hparams['dataset_folder'], num_input_images=self.hparams['num_input_images'], num_output_images=self.hparams['num_output_images'], train=True, transform=valid_transform ) num_train = len(self.train_dataset) indices = list(range(num_train)) split = int(np.floor(self.hparams['valid_size'] * num_train)) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] self.train_sampler = SubsetRandomSampler(train_idx) self.valid_sampler = SubsetRandomSampler(valid_idx) def train_dataloader(self): train_loader = torch.utils.data.DataLoader( self.train_dataset, batch_size=self.hparams['batch_size'], sampler=self.train_sampler, num_workers=2, pin_memory=True ) return train_loader def val_dataloader(self): valid_loader = torch.utils.data.DataLoader( self.valid_dataset, batch_size=self.hparams['batch_size'], sampler=self.valid_sampler, num_workers=2, pin_memory=True ) return valid_loader def test_dataloader(self): test_loader = torch.utils.data.DataLoader( self.test_dataset, batch_size=self.hparams['batch_size'], sampler=self.test_sampler, num_workers=2, pin_memory=True ) return test_loader
Precipitation Forecasting/precipitation_lightning_base.py
import torch from torch.utils.data import SubsetRandomSampler import numpy as np from Precipitation_Forecasting.precipitation_dataset import precipitation_maps_oversampled_h5 from Precipitation_Forecasting.precipitation_lightning import AA_TransUnet_base class Precip_regression_base(TransUnet_base): def __init__(self, hparams): super(Precip_regression_base, self).__init__(hparams=hparams) self.train_dataset = None self.valid_dataset = None self.train_sampler = None self.valid_sampler = None def prepare_data(self): train_transform = None valid_transform = None if self.hparams['use_oversampled_dataset']: self.train_dataset = precipitation_maps_oversampled_h5( in_file=self.hparams['dataset_folder'], num_input_images=self.hparams['num_input_images'], num_output_images=self.hparams['num_output_images'], train=True, transform=train_transform ) self.valid_dataset = precipitation_maps_oversampled_h5( in_file=self.hparams['dataset_folder'], num_input_images=self.hparams['num_input_images'], num_output_images=self.hparams['num_output_images'], train=True, transform=valid_transform ) num_train = len(self.train_dataset) indices = list(range(num_train)) split = int(np.floor(self.hparams['valid_size'] * num_train)) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] self.train_sampler = SubsetRandomSampler(train_idx) self.valid_sampler = SubsetRandomSampler(valid_idx) def train_dataloader(self): train_loader = torch.utils.data.DataLoader( self.train_dataset, batch_size=self.hparams['batch_size'], sampler=self.train_sampler, num_workers=2, pin_memory=True ) return train_loader def val_dataloader(self): valid_loader = torch.utils.data.DataLoader( self.valid_dataset, batch_size=self.hparams['batch_size'], sampler=self.valid_sampler, num_workers=2, pin_memory=True ) return valid_loader def test_dataloader(self): test_loader = torch.utils.data.DataLoader( self.test_dataset, batch_size=self.hparams['batch_size'], sampler=self.test_sampler, num_workers=2, pin_memory=True ) return test_loader
0.776284
0.394726
import serial, glob import copy import json import time from time import localtime, strftime #initialization and open the port #possible timeout values: # 1. None: wait forever, block call # 2. 0: non-blocking mode, return immediately # 3. x, x is bigger than 0, float allowed, timeout block call temp_list = glob.glob ('/dev/ttyACM*') print temp_list ser = serial.Serial() ser.port = "/dev/ttyACM0" # ser.port = "/dev/ttyUSB7" #ser.port = "/dev/ttyS2" ser.baudrate = 115200 ser.bytesize = serial.EIGHTBITS #number of bits per bytes ser.parity = serial.PARITY_NONE #set parity check: no parity ser.stopbits = serial.STOPBITS_ONE #number of stop bits #ser.timeout = None #block read ser.timeout = 1 #non-block read #ser.timeout = 2 #timeout block read ser.xonxoff = False #disable software flow control ser.rtscts = False #disable hardware (RTS/CTS) flow control ser.dsrdtr = False #disable hardware (DSR/DTR) flow control ser.writeTimeout = 2 #timeout for write arrayName = ["pH", "Soil Humidity", "Soil Temperature", "uV", " Air Humidity", "Air Temperature"] addressNode = [] dataNode = [] jsonNode = {} jsonSample = {} jsonSensor = {} def setVarBuff(): global jsonNode, jsonSample, jsonSensor jsonNode = { "name": "", "payload":{} } jsonSample = { "payload": { } } jsonSensor = { "name": "", "value": 0 } def resetVarBuff(): global jsonNode, jsonSample, jsonSensor addressNode = [] dataNode = [] jsonNode = {} jsonSample = {} jsonSensor = {} def operator(addressNode): if len(addressNode)>0: setVarBuff() for i in range(0,len(addressNode)): jsontemp = copy.deepcopy(jsonNode) jsontemp['name'] = addressNode[i] for x in range(0,6): jsonTempSensor = copy.deepcopy(jsonSensor) jsonTempSensor['name'] = arrayName[x] jsonTempSensor['value'] = dataNode[i][x] jsontemp['payload'].update({"sensor_0"+str(x+1):jsonTempSensor}) jsontemp.update({"rightNow": strftime("%Y-%m-%d %H:%M:%S", localtime())}) jsonSample['payload'].update({"Node_0"+str(i+1):jsontemp}) def check_frame(line): if line.find("***|") != -1: # check Start if line.find("|***") != -1: # check stop return True return False return False def getUart_CC1350(): count = 0 if ser.inWaiting()>0: time.sleep(5) # Time to waiting buffer is done setVarBuff() #set when get data, reset when send data to Cloud for the next time while ser.inWaiting()>0: line = ser.readline() if check_frame(line): start = time.time() line = line.replace('\r\n','').replace("***|","").replace("|***","") array = line.split('|') # print array nameNode = array.pop(0) if nameNode in addressNode: dataNode[addressNode.index(nameNode)] = array # print dataNode else: addressNode.append(nameNode) dataNode.append([]) dataNode[addressNode.index(nameNode)] = array count+=1 print "Time to get Uart: " + str(time.time() - start) else: print "It's not my frame." if count>0: operator(addressNode) return True else: print "Nothing" return False if __name__ == '__main__': try: ser.open() except Exception as e: ser.close() ser.open() if ser.isOpen(): ser.flushInput() #flush input buffer, discarding all its contents ser.flushOutput() #flush output buffer, aborting current output while ser.inWaiting()>0: time.sleep(0.5) #give the serial port sometime to receive the data temp = ser.read(ser.inWaiting()) del temp while True: time.sleep(3) # do another thing if ser.isOpen(): if getUart_CC1350(): print json.dumps(jsonSample,sort_keys=True, indent=4, separators=(',',':')) resetVarBuff() else: print "Nothing" else: print "cannot open serial port "
test_uart/uart1.py
import serial, glob import copy import json import time from time import localtime, strftime #initialization and open the port #possible timeout values: # 1. None: wait forever, block call # 2. 0: non-blocking mode, return immediately # 3. x, x is bigger than 0, float allowed, timeout block call temp_list = glob.glob ('/dev/ttyACM*') print temp_list ser = serial.Serial() ser.port = "/dev/ttyACM0" # ser.port = "/dev/ttyUSB7" #ser.port = "/dev/ttyS2" ser.baudrate = 115200 ser.bytesize = serial.EIGHTBITS #number of bits per bytes ser.parity = serial.PARITY_NONE #set parity check: no parity ser.stopbits = serial.STOPBITS_ONE #number of stop bits #ser.timeout = None #block read ser.timeout = 1 #non-block read #ser.timeout = 2 #timeout block read ser.xonxoff = False #disable software flow control ser.rtscts = False #disable hardware (RTS/CTS) flow control ser.dsrdtr = False #disable hardware (DSR/DTR) flow control ser.writeTimeout = 2 #timeout for write arrayName = ["pH", "Soil Humidity", "Soil Temperature", "uV", " Air Humidity", "Air Temperature"] addressNode = [] dataNode = [] jsonNode = {} jsonSample = {} jsonSensor = {} def setVarBuff(): global jsonNode, jsonSample, jsonSensor jsonNode = { "name": "", "payload":{} } jsonSample = { "payload": { } } jsonSensor = { "name": "", "value": 0 } def resetVarBuff(): global jsonNode, jsonSample, jsonSensor addressNode = [] dataNode = [] jsonNode = {} jsonSample = {} jsonSensor = {} def operator(addressNode): if len(addressNode)>0: setVarBuff() for i in range(0,len(addressNode)): jsontemp = copy.deepcopy(jsonNode) jsontemp['name'] = addressNode[i] for x in range(0,6): jsonTempSensor = copy.deepcopy(jsonSensor) jsonTempSensor['name'] = arrayName[x] jsonTempSensor['value'] = dataNode[i][x] jsontemp['payload'].update({"sensor_0"+str(x+1):jsonTempSensor}) jsontemp.update({"rightNow": strftime("%Y-%m-%d %H:%M:%S", localtime())}) jsonSample['payload'].update({"Node_0"+str(i+1):jsontemp}) def check_frame(line): if line.find("***|") != -1: # check Start if line.find("|***") != -1: # check stop return True return False return False def getUart_CC1350(): count = 0 if ser.inWaiting()>0: time.sleep(5) # Time to waiting buffer is done setVarBuff() #set when get data, reset when send data to Cloud for the next time while ser.inWaiting()>0: line = ser.readline() if check_frame(line): start = time.time() line = line.replace('\r\n','').replace("***|","").replace("|***","") array = line.split('|') # print array nameNode = array.pop(0) if nameNode in addressNode: dataNode[addressNode.index(nameNode)] = array # print dataNode else: addressNode.append(nameNode) dataNode.append([]) dataNode[addressNode.index(nameNode)] = array count+=1 print "Time to get Uart: " + str(time.time() - start) else: print "It's not my frame." if count>0: operator(addressNode) return True else: print "Nothing" return False if __name__ == '__main__': try: ser.open() except Exception as e: ser.close() ser.open() if ser.isOpen(): ser.flushInput() #flush input buffer, discarding all its contents ser.flushOutput() #flush output buffer, aborting current output while ser.inWaiting()>0: time.sleep(0.5) #give the serial port sometime to receive the data temp = ser.read(ser.inWaiting()) del temp while True: time.sleep(3) # do another thing if ser.isOpen(): if getUart_CC1350(): print json.dumps(jsonSample,sort_keys=True, indent=4, separators=(',',':')) resetVarBuff() else: print "Nothing" else: print "cannot open serial port "
0.156169
0.098209
import contribution.utils from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='Contribution', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=30, verbose_name='title')), ('file', models.FileField(upload_to=contribution.utils.upload_contribution_path, verbose_name='file')), ('slug', models.SlugField(unique=True, verbose_name='slug')), ('is_commented', models.BooleanField(default=False, verbose_name='is commented')), ('is_selected', models.BooleanField(default=False, verbose_name='is selected')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ], options={ 'verbose_name': 'Contribution', 'verbose_name_plural': 'Contributions', 'ordering': ['-updated_at'], }, ), migrations.CreateModel( name='ContributionCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_for', models.PositiveSmallIntegerField(choices=[(0, 'Documents'), (1, 'Images')], default=0, verbose_name='category for')), ('title', models.CharField(max_length=23, verbose_name='title')), ('slug', models.SlugField(unique=True, verbose_name='slug')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ], options={ 'verbose_name': 'Contribution Category', 'verbose_name_plural': 'Contribution Categories', 'ordering': ['-created_at'], }, ), migrations.AddField( model_name='contribution', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='contribution_category', to='contribution.ContributionCategory', verbose_name='category'), ), migrations.AddField( model_name='contribution', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_contribution', to='accounts.UserProfile', verbose_name='user'), ), ]
contribution/migrations/0001_initial.py
import contribution.utils from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='Contribution', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=30, verbose_name='title')), ('file', models.FileField(upload_to=contribution.utils.upload_contribution_path, verbose_name='file')), ('slug', models.SlugField(unique=True, verbose_name='slug')), ('is_commented', models.BooleanField(default=False, verbose_name='is commented')), ('is_selected', models.BooleanField(default=False, verbose_name='is selected')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ], options={ 'verbose_name': 'Contribution', 'verbose_name_plural': 'Contributions', 'ordering': ['-updated_at'], }, ), migrations.CreateModel( name='ContributionCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_for', models.PositiveSmallIntegerField(choices=[(0, 'Documents'), (1, 'Images')], default=0, verbose_name='category for')), ('title', models.CharField(max_length=23, verbose_name='title')), ('slug', models.SlugField(unique=True, verbose_name='slug')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ], options={ 'verbose_name': 'Contribution Category', 'verbose_name_plural': 'Contribution Categories', 'ordering': ['-created_at'], }, ), migrations.AddField( model_name='contribution', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='contribution_category', to='contribution.ContributionCategory', verbose_name='category'), ), migrations.AddField( model_name='contribution', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_contribution', to='accounts.UserProfile', verbose_name='user'), ), ]
0.521959
0.136522
import math import operator from functools import reduce def cached_pure_function(fn): cache = {} def wrapper(*args): if args in cache: return cache[args] x = fn(*args) cache[args] = x return x return wrapper def cached_pure_generator(fn): caches = {} iterator = fn() def wrapper(*args): index = 0 if args not in caches: caches[args] = [] cache = caches[args] while True: if index < len(cache): n = cache[index] else: n = next(iterator) cache.append(n) yield n index += 1 return wrapper def digit_product(n): return reduce(operator.mul, [digit for digit in digits(n)]) def digit_sum(n): return reduce(operator.add, [digit for digit in digits(n)]) def digits(n): for digit in str(n): yield int(digit) def euler_phi(n): if n < 1: return 0 if n == 1: return 1 x = 0 for i in range(1, n): if is_coprime(n, i): x += 1 return x @cached_pure_function def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False # IDEA: Would checking only for prime factors be an optimization here? # TODO: Leverage yield_prime() recursively or cache known primes # SEE: https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic for i in range(3, math.ceil(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True def is_coprime(a, b): a = prime_factorization(a) b = prime_factorization(b) for n in a: if n in b: return False return True def is_square(n): sqrt = math.sqrt(n) return sqrt == math.floor(sqrt) def prime_factorization(n, multiplicity = False): if n <= 1: return [] if is_prime(n): return [n] result = [] for i in yield_prime(): appended = False while n % i == 0: if multiplicity or not appended: result.append(i) appended = True n /= i if n == 1: return result def yield_prime(): n = 2 while True: if is_prime(n): yield n n += 1
intseq/utility.py
import math import operator from functools import reduce def cached_pure_function(fn): cache = {} def wrapper(*args): if args in cache: return cache[args] x = fn(*args) cache[args] = x return x return wrapper def cached_pure_generator(fn): caches = {} iterator = fn() def wrapper(*args): index = 0 if args not in caches: caches[args] = [] cache = caches[args] while True: if index < len(cache): n = cache[index] else: n = next(iterator) cache.append(n) yield n index += 1 return wrapper def digit_product(n): return reduce(operator.mul, [digit for digit in digits(n)]) def digit_sum(n): return reduce(operator.add, [digit for digit in digits(n)]) def digits(n): for digit in str(n): yield int(digit) def euler_phi(n): if n < 1: return 0 if n == 1: return 1 x = 0 for i in range(1, n): if is_coprime(n, i): x += 1 return x @cached_pure_function def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False # IDEA: Would checking only for prime factors be an optimization here? # TODO: Leverage yield_prime() recursively or cache known primes # SEE: https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic for i in range(3, math.ceil(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True def is_coprime(a, b): a = prime_factorization(a) b = prime_factorization(b) for n in a: if n in b: return False return True def is_square(n): sqrt = math.sqrt(n) return sqrt == math.floor(sqrt) def prime_factorization(n, multiplicity = False): if n <= 1: return [] if is_prime(n): return [n] result = [] for i in yield_prime(): appended = False while n % i == 0: if multiplicity or not appended: result.append(i) appended = True n /= i if n == 1: return result def yield_prime(): n = 2 while True: if is_prime(n): yield n n += 1
0.35768
0.306598
from __future__ import unicode_literals, print_function import logging from os import path import os import subprocess as sp import sys from chalmers import errors import tempfile python_exe = sys.executable chalmers_script = sys.argv[0] def read_data(filename): filename = path.join(path.dirname(__file__), 'data', filename) with open(filename) as fd: return fd.read() launchd_label = "org.continuum.chalmers" log = logging.getLogger('chalmers.service') class DarwinService(object): def __init__(self, target_user): self.target_user = target_user log.info('Platform: Darwin') log.info('Using Darwin launchd service') if target_user: log.info('Launching chalmers as target user %s' % target_user) elif target_user is False: log.info('Launching chalmers as current user (does not require root)') else: log.info('Launching chalmers as root user') @property def label(self): if self.target_user: return '%s.%s' % (launchd_label, self.target_user) else: return launchd_label @property def template(self): return read_data('launchd.plist') def check_output(self, command): if self.target_user: if os.getuid() != 0: raise errors.ChalmersError("Can not perform system install without root") log.info("Running command: %s" % ' '.join(command)) try: output = sp.check_output(command, stderr=sp.STDOUT) except OSError as err: raise errors.ChalmersError("Could not access program 'launchctl' required for osx service install") except sp.CalledProcessError as err: if err.returncode == 1: if 'Socket is not connected' in err.output: log.error(err.output) raise errors.ChalmersError("The user '%s' must be logged in via the osx gui to perform this operation" % self.target_user) raise return output def get_launchd(self): try: command = ['launchctl', 'list', self.label] return self.check_output(command) except sp.CalledProcessError as err: if err.returncode == 1: return None raise def add_launchd(self): if self.target_user: username = '<key>UserName</key> <string>%s</string>' % self.target_user else: username = '' plist = self.template.format(python_exe=python_exe, chalmers=chalmers_script, label=self.label, username=username) with tempfile.NamedTemporaryFile('w', suffix='.plist', prefix='chalmers') as fd: fd.write(plist) fd.flush() try: command = ['launchctl', 'load', fd.name] self.check_output(command).strip() except sp.CalledProcessError as err: if err.returncode == 1: raise errors.ChalmersError("Chalmers service is already installed") raise def install(self): """Create a launchd plist and load as a global daemon""" log.info("Adding chalmers launchd plist") self.add_launchd() log.info("All chalmers programs will now run on boot") return True def uninstall(self): """Uninstall launchd plist for chalmers""" log.info("Removing chalmers plist from launchd") try: command = ['launchctl', 'remove', self.label] self.check_output(command).strip() except sp.CalledProcessError as err: if err.returncode == 1: log.error("Chalmers service is not installed") return False raise log.info("Chalmers service has been removed") return True def status(self): """Check if chalmers will be started at reboot""" try: launchd_lines = self.get_launchd() except sp.CalledProcessError: launchd_lines = None if launchd_lines: log.info("Chalmers is setup to start on boot") return True else: log.info("Chalmers will not start on boot") return False
chalmers/service/darwin_service.py
from __future__ import unicode_literals, print_function import logging from os import path import os import subprocess as sp import sys from chalmers import errors import tempfile python_exe = sys.executable chalmers_script = sys.argv[0] def read_data(filename): filename = path.join(path.dirname(__file__), 'data', filename) with open(filename) as fd: return fd.read() launchd_label = "org.continuum.chalmers" log = logging.getLogger('chalmers.service') class DarwinService(object): def __init__(self, target_user): self.target_user = target_user log.info('Platform: Darwin') log.info('Using Darwin launchd service') if target_user: log.info('Launching chalmers as target user %s' % target_user) elif target_user is False: log.info('Launching chalmers as current user (does not require root)') else: log.info('Launching chalmers as root user') @property def label(self): if self.target_user: return '%s.%s' % (launchd_label, self.target_user) else: return launchd_label @property def template(self): return read_data('launchd.plist') def check_output(self, command): if self.target_user: if os.getuid() != 0: raise errors.ChalmersError("Can not perform system install without root") log.info("Running command: %s" % ' '.join(command)) try: output = sp.check_output(command, stderr=sp.STDOUT) except OSError as err: raise errors.ChalmersError("Could not access program 'launchctl' required for osx service install") except sp.CalledProcessError as err: if err.returncode == 1: if 'Socket is not connected' in err.output: log.error(err.output) raise errors.ChalmersError("The user '%s' must be logged in via the osx gui to perform this operation" % self.target_user) raise return output def get_launchd(self): try: command = ['launchctl', 'list', self.label] return self.check_output(command) except sp.CalledProcessError as err: if err.returncode == 1: return None raise def add_launchd(self): if self.target_user: username = '<key>UserName</key> <string>%s</string>' % self.target_user else: username = '' plist = self.template.format(python_exe=python_exe, chalmers=chalmers_script, label=self.label, username=username) with tempfile.NamedTemporaryFile('w', suffix='.plist', prefix='chalmers') as fd: fd.write(plist) fd.flush() try: command = ['launchctl', 'load', fd.name] self.check_output(command).strip() except sp.CalledProcessError as err: if err.returncode == 1: raise errors.ChalmersError("Chalmers service is already installed") raise def install(self): """Create a launchd plist and load as a global daemon""" log.info("Adding chalmers launchd plist") self.add_launchd() log.info("All chalmers programs will now run on boot") return True def uninstall(self): """Uninstall launchd plist for chalmers""" log.info("Removing chalmers plist from launchd") try: command = ['launchctl', 'remove', self.label] self.check_output(command).strip() except sp.CalledProcessError as err: if err.returncode == 1: log.error("Chalmers service is not installed") return False raise log.info("Chalmers service has been removed") return True def status(self): """Check if chalmers will be started at reboot""" try: launchd_lines = self.get_launchd() except sp.CalledProcessError: launchd_lines = None if launchd_lines: log.info("Chalmers is setup to start on boot") return True else: log.info("Chalmers will not start on boot") return False
0.286968
0.085939
import time, json from collections import OrderedDict as od class kormerDict: def __init__(self): self._1mer_ = {} self._2mer_ = {} self._3mer_ = {} def getData(self,fname): self.fname = fname with open(self.fname, "r") as rf : self._udict_ = json.load(rf) self.kl = list(self._udict_.keys()) def dict1Mer(self): for word in self.kl : for chr in word: if chr not in self._1mer_ : self._1mer_ [chr]=1 else : self._1mer_ [chr]+=1 def dict2Mer(self): for word in self.kl : word = "_"+word+"_" for i in range(len(word)): e = i+1 if e > len(word)-1: break else : if word[i:e+1] not in self._2mer_ : self._2mer_ [word[i:e+1]]=1 else : self._2mer_ [word[i:e+1]]+=1 def dict3Mer(self): for word in self.kl : word = "_"+word+"_" for i in range(len(word)): e = i+2 if e > len(word)-1: break else : if word[i:e+1] not in self._3mer_ : self._3mer_ [word[i:e+1]]=1 else : self._3mer_ [word[i:e+1]]+=1 def colDict(self, dicName): self._1mer_ = dict(od(sorted(self._1mer_.items(), key=lambda t: t[0]))) self._2mer_ = dict(od(sorted(self._2mer_.items(), key=lambda t: t[0]))) self._3mer_ = dict(od(sorted(self._3mer_.items(), key=lambda t: t[0]))) with open("Joongang"+ dicName + "Py.json", "a", encoding="utf-8") as jwf: if dicName == "1merDic": print("1merDic 제시어 수 :", len(self._1mer_)) jwf.write(json.dumps(self._1mer_)) elif dicName == "2merDic": print("2merDic 제시어 수 :", len(self._2mer_)) jwf.write(json.dumps(self._2mer_)) elif dicName == "3merDic": print("3merDic 제시어 수 :", len(self._3mer_)) jwf.write(json.dumps(self._3mer_)) with open("Joongang"+ dicName + ".txt", "a", encoding="utf-8") as twf: if dicName == "1merDic": for k, v in self._1mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") elif dicName == "2merDic": for k, v in self._2mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") elif dicName == "3merDic": for k,v in self._3mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") def main(): beg = time.time() ex = kormerDict() for i in range(1,29+1): ex.getData("중앙기사%dResPy.json" % i) ex.dict1Mer() ex.dict2Mer() ex.dict3Mer() ex.colDict("1merDic") ex.colDict("2merDic") ex.colDict("3merDic") end = time.time() print("exec time : %.6g sec(s)" % (end-beg)) return if __name__ == '__main__': main()
kormerDict.py
import time, json from collections import OrderedDict as od class kormerDict: def __init__(self): self._1mer_ = {} self._2mer_ = {} self._3mer_ = {} def getData(self,fname): self.fname = fname with open(self.fname, "r") as rf : self._udict_ = json.load(rf) self.kl = list(self._udict_.keys()) def dict1Mer(self): for word in self.kl : for chr in word: if chr not in self._1mer_ : self._1mer_ [chr]=1 else : self._1mer_ [chr]+=1 def dict2Mer(self): for word in self.kl : word = "_"+word+"_" for i in range(len(word)): e = i+1 if e > len(word)-1: break else : if word[i:e+1] not in self._2mer_ : self._2mer_ [word[i:e+1]]=1 else : self._2mer_ [word[i:e+1]]+=1 def dict3Mer(self): for word in self.kl : word = "_"+word+"_" for i in range(len(word)): e = i+2 if e > len(word)-1: break else : if word[i:e+1] not in self._3mer_ : self._3mer_ [word[i:e+1]]=1 else : self._3mer_ [word[i:e+1]]+=1 def colDict(self, dicName): self._1mer_ = dict(od(sorted(self._1mer_.items(), key=lambda t: t[0]))) self._2mer_ = dict(od(sorted(self._2mer_.items(), key=lambda t: t[0]))) self._3mer_ = dict(od(sorted(self._3mer_.items(), key=lambda t: t[0]))) with open("Joongang"+ dicName + "Py.json", "a", encoding="utf-8") as jwf: if dicName == "1merDic": print("1merDic 제시어 수 :", len(self._1mer_)) jwf.write(json.dumps(self._1mer_)) elif dicName == "2merDic": print("2merDic 제시어 수 :", len(self._2mer_)) jwf.write(json.dumps(self._2mer_)) elif dicName == "3merDic": print("3merDic 제시어 수 :", len(self._3mer_)) jwf.write(json.dumps(self._3mer_)) with open("Joongang"+ dicName + ".txt", "a", encoding="utf-8") as twf: if dicName == "1merDic": for k, v in self._1mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") elif dicName == "2merDic": for k, v in self._2mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") elif dicName == "3merDic": for k,v in self._3mer_.items(): twf.write(f"{k:>1s} {v:<6d}\n") def main(): beg = time.time() ex = kormerDict() for i in range(1,29+1): ex.getData("중앙기사%dResPy.json" % i) ex.dict1Mer() ex.dict2Mer() ex.dict3Mer() ex.colDict("1merDic") ex.colDict("2merDic") ex.colDict("3merDic") end = time.time() print("exec time : %.6g sec(s)" % (end-beg)) return if __name__ == '__main__': main()
0.054588
0.154217
from profileapi.models import Profile from profileapi.serializers import ProfileSerializer from rest_framework import generics, status from rest_framework.response import Response from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.csrf import csrf_exempt class Profiles(generics.ListCreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer search_fields = ('^username',) def create(self, request, *args, **kwargs): """ Create a new user with given data. Returns all relevant data. """ # check date is valid serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) try: serializer.save() except ValueError as e: return Response({'success': 'False', 'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) headers = self.get_success_headers(serializer.data) response_data = { "success": "True", "message": "Profile Created", "profile": serializer.data } return Response(response_data, status=status.HTTP_201_CREATED, headers=headers) def get(self, request): """ Return profile information for given user """ serializer = ProfileSerializer(self.request.data['username']) return Response(serializer.data) class Login(generics.ListCreateAPIView): @csrf_exempt def create(self, request): """ Login view - verifies tha user is valid and returns information about user for profile page setup. """ try: user = Profile.objects.get(username=self.request.data["username"]) except ObjectDoesNotExist: return Response({'success': 'false','message':'User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) if user.password == self.request.data["password"]: serializer = ProfileSerializer(user) return Response(serializer.data) else: return Response({'success':'false', 'message':'Password is incorrect.'})
taskit_backend/profileapi/views.py
from profileapi.models import Profile from profileapi.serializers import ProfileSerializer from rest_framework import generics, status from rest_framework.response import Response from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.csrf import csrf_exempt class Profiles(generics.ListCreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer search_fields = ('^username',) def create(self, request, *args, **kwargs): """ Create a new user with given data. Returns all relevant data. """ # check date is valid serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) try: serializer.save() except ValueError as e: return Response({'success': 'False', 'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) headers = self.get_success_headers(serializer.data) response_data = { "success": "True", "message": "Profile Created", "profile": serializer.data } return Response(response_data, status=status.HTTP_201_CREATED, headers=headers) def get(self, request): """ Return profile information for given user """ serializer = ProfileSerializer(self.request.data['username']) return Response(serializer.data) class Login(generics.ListCreateAPIView): @csrf_exempt def create(self, request): """ Login view - verifies tha user is valid and returns information about user for profile page setup. """ try: user = Profile.objects.get(username=self.request.data["username"]) except ObjectDoesNotExist: return Response({'success': 'false','message':'User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) if user.password == self.request.data["password"]: serializer = ProfileSerializer(user) return Response(serializer.data) else: return Response({'success':'false', 'message':'Password is incorrect.'})
0.689096
0.117521
class FileLoader(object): def __init__(self, fname, coltypes = {}, separator = None): self.types = coltypes if type(fname) == str: ofile = open(fname) else: ofile = fname self.rows = [x.split(separator) for x in ofile] def __getitem__(self, *args): index = args[0] if type(index) != int: raise TypeError("The index must be an integer, but I got '%s'" % index) row = tuple(self.types.get(colno, str)(colval) for (colno, colval) in enumerate(self.rows[index])) return row def __iter__(self): class IterObject(object): def __init__(self, fl): self.iterable = fl self.pointer = 0 def next(self): try: val = self.iterable[self.pointer] self.pointer += 1 return val except IndexError: raise StopIteration return IterObject(self) class WheelLoader(object): def __init__(self, fname): if type(fname) == str: ofile = open(fname) else: ofile = fname self.rows = [self.splitRow(x) for x in ofile] def splitRow(self, string): elements = [] partial = string.lstrip() while partial: if partial[0] == "'": elem, partial = self.__processString(partial) else: elem, partial = [x.lstrip() for x in self.__processNonString(partial)] elements.append(elem) return elements def __processNonString(self, string): splitted = string.split(' ', 1) if len(splitted) < 2: rest = "" else: rest = splitted[1].lstrip() return splitted[0].strip(), rest def __processString(self, string): retval = "" done = False partial = string[1:] while not done: end = partial.find("'") if end == -1: raise ValueError("Missing end quote in [%s]" % string) retval += partial[:end] partial = partial[end+1:] if partial.startswith("'"): retval += "'" partial = partial[end+1:] if not partial.startswith(" "): retval += "'" else: partial = partial.lstrip() done = True return retval, partial def __getitem__(self, *args): index = args[0] if type(index) != int: raise TypeError("The index must be an integer, but I got '%s'" % index) return tuple(self.rows[index]) def __iter__(self): class IterObject(object): def __init__(self, fl): self.iterable = fl self.pointer = 0 def next(self): try: val = self.iterable[self.pointer] self.pointer += 1 return val except IndexError: raise StopIteration return IterObject(self) example_file = """0 1050.0 1013.92 1 1050.0 1025.65 2 1138.3 1010.90 3 1118.9 1050.0 4 1119.0 995.0 5 1050.0 1006.98 6 1050.0 1015.05 7 1050.0 1011.7 9 1021.0 880.0 10 1182.0 997.0 11 1116.0 999.9 12 1132.0 996.8 13 1220.0 992.0 14 750.0 1003.7 15 1107.0 902.1 16 999.9 999.8 17 1050.0 1015.0 33 1212. 1212.4 34 1086. 1080. 37 1152. 1370. 40 687. 1011. 55 1063.05 936.63 66 1181.69 1266.05 77 1175.0 1047.0 88 1103.9 1025.0 """ example_wheel_file = """0 'Open' 0 1 'Hal_rs45 696_5' 58 2 'u'_Slo 350_65' 82 3 'u'_Slo 353_55' 109 4 'Halp 656_3' 21 5 'Cont 662_4' 77 6 '[SII] 672_5' 123 """ if __name__ == '__main__': from StringIO import StringIO print "Sample: 6th row with no converters" print FileLoader(StringIO(example_file))[5] print print "Sample: 6th row with converters = {0: int, 1:float}" print FileLoader(StringIO(example_file), coltypes = {0: int, 1:float})[5] print print "Sample: Iterate over the whole file; converters = {0: int, 1:float, 2:float}" fl = FileLoader(StringIO(example_file), coltypes = {0: int, 1:float, 2:float}) for tpl in fl: print tpl print "Sample: Iterate over a wheel file" fl = WheelLoader(StringIO(example_wheel_file)) for tpl in fl: print tpl
sandbox/src2/src/fileloader.py
class FileLoader(object): def __init__(self, fname, coltypes = {}, separator = None): self.types = coltypes if type(fname) == str: ofile = open(fname) else: ofile = fname self.rows = [x.split(separator) for x in ofile] def __getitem__(self, *args): index = args[0] if type(index) != int: raise TypeError("The index must be an integer, but I got '%s'" % index) row = tuple(self.types.get(colno, str)(colval) for (colno, colval) in enumerate(self.rows[index])) return row def __iter__(self): class IterObject(object): def __init__(self, fl): self.iterable = fl self.pointer = 0 def next(self): try: val = self.iterable[self.pointer] self.pointer += 1 return val except IndexError: raise StopIteration return IterObject(self) class WheelLoader(object): def __init__(self, fname): if type(fname) == str: ofile = open(fname) else: ofile = fname self.rows = [self.splitRow(x) for x in ofile] def splitRow(self, string): elements = [] partial = string.lstrip() while partial: if partial[0] == "'": elem, partial = self.__processString(partial) else: elem, partial = [x.lstrip() for x in self.__processNonString(partial)] elements.append(elem) return elements def __processNonString(self, string): splitted = string.split(' ', 1) if len(splitted) < 2: rest = "" else: rest = splitted[1].lstrip() return splitted[0].strip(), rest def __processString(self, string): retval = "" done = False partial = string[1:] while not done: end = partial.find("'") if end == -1: raise ValueError("Missing end quote in [%s]" % string) retval += partial[:end] partial = partial[end+1:] if partial.startswith("'"): retval += "'" partial = partial[end+1:] if not partial.startswith(" "): retval += "'" else: partial = partial.lstrip() done = True return retval, partial def __getitem__(self, *args): index = args[0] if type(index) != int: raise TypeError("The index must be an integer, but I got '%s'" % index) return tuple(self.rows[index]) def __iter__(self): class IterObject(object): def __init__(self, fl): self.iterable = fl self.pointer = 0 def next(self): try: val = self.iterable[self.pointer] self.pointer += 1 return val except IndexError: raise StopIteration return IterObject(self) example_file = """0 1050.0 1013.92 1 1050.0 1025.65 2 1138.3 1010.90 3 1118.9 1050.0 4 1119.0 995.0 5 1050.0 1006.98 6 1050.0 1015.05 7 1050.0 1011.7 9 1021.0 880.0 10 1182.0 997.0 11 1116.0 999.9 12 1132.0 996.8 13 1220.0 992.0 14 750.0 1003.7 15 1107.0 902.1 16 999.9 999.8 17 1050.0 1015.0 33 1212. 1212.4 34 1086. 1080. 37 1152. 1370. 40 687. 1011. 55 1063.05 936.63 66 1181.69 1266.05 77 1175.0 1047.0 88 1103.9 1025.0 """ example_wheel_file = """0 'Open' 0 1 'Hal_rs45 696_5' 58 2 'u'_Slo 350_65' 82 3 'u'_Slo 353_55' 109 4 'Halp 656_3' 21 5 'Cont 662_4' 77 6 '[SII] 672_5' 123 """ if __name__ == '__main__': from StringIO import StringIO print "Sample: 6th row with no converters" print FileLoader(StringIO(example_file))[5] print print "Sample: 6th row with converters = {0: int, 1:float}" print FileLoader(StringIO(example_file), coltypes = {0: int, 1:float})[5] print print "Sample: Iterate over the whole file; converters = {0: int, 1:float, 2:float}" fl = FileLoader(StringIO(example_file), coltypes = {0: int, 1:float, 2:float}) for tpl in fl: print tpl print "Sample: Iterate over a wheel file" fl = WheelLoader(StringIO(example_wheel_file)) for tpl in fl: print tpl
0.45423
0.167695
from typing import Type, Optional, Dict, Any, Iterator from marshy.errors import MarshallError from marshy.factory import marshaller_factory_abc from marshy.factory.marshaller_factory_abc import MarshallerFactoryABC from marshy.marshaller import marshaller_abc from marshy.types import ExternalType from marshy.utils import resolve_forward_refs class MarshallerContext: def __init__(self, factories: Optional[marshaller_factory_abc.MarshallerFactoryABC] = None, by_type: Optional[Dict[Type, marshaller_abc.MarshallerABC]] = None): self._factories = sorted(factories or [], reverse=True) self._by_type = dict(by_type or {}) def register_factory(self, marshaller_factory: marshaller_factory_abc.MarshallerFactoryABC): self._factories.append(marshaller_factory) self._factories = sorted(self._factories or [], reverse=True) def register_marshaller(self, marshaller: marshaller_abc.MarshallerABC, type_: Type = None): type_ = type_ or marshaller.marshalled_type self._by_type[type_] = marshaller def get_marshaller(self, type_: Type) -> marshaller_abc.MarshallerABC: marshaller = self._by_type.get(type_) if not marshaller: resolved_type = resolve_forward_refs(type_) for factory in self._factories: marshaller = factory.create(self, resolved_type) if marshaller: break if not marshaller: raise MarshallError(f'NoMarshallerForType:{type_}') self._by_type[type_] = marshaller return marshaller def load(self, type_: Type, to_load: ExternalType): marshaller = self.get_marshaller(type_) loaded = marshaller.load(to_load) return loaded def dump(self, obj: Any, type_: Optional[Type] = None) -> ExternalType: if not type_: type_ = type(obj) marshaller = self.get_marshaller(type_) dumped = marshaller.dump(obj) return dumped def get_factories(self) -> Iterator[MarshallerFactoryABC]: return iter(self._factories)
marshy/marshaller_context.py
from typing import Type, Optional, Dict, Any, Iterator from marshy.errors import MarshallError from marshy.factory import marshaller_factory_abc from marshy.factory.marshaller_factory_abc import MarshallerFactoryABC from marshy.marshaller import marshaller_abc from marshy.types import ExternalType from marshy.utils import resolve_forward_refs class MarshallerContext: def __init__(self, factories: Optional[marshaller_factory_abc.MarshallerFactoryABC] = None, by_type: Optional[Dict[Type, marshaller_abc.MarshallerABC]] = None): self._factories = sorted(factories or [], reverse=True) self._by_type = dict(by_type or {}) def register_factory(self, marshaller_factory: marshaller_factory_abc.MarshallerFactoryABC): self._factories.append(marshaller_factory) self._factories = sorted(self._factories or [], reverse=True) def register_marshaller(self, marshaller: marshaller_abc.MarshallerABC, type_: Type = None): type_ = type_ or marshaller.marshalled_type self._by_type[type_] = marshaller def get_marshaller(self, type_: Type) -> marshaller_abc.MarshallerABC: marshaller = self._by_type.get(type_) if not marshaller: resolved_type = resolve_forward_refs(type_) for factory in self._factories: marshaller = factory.create(self, resolved_type) if marshaller: break if not marshaller: raise MarshallError(f'NoMarshallerForType:{type_}') self._by_type[type_] = marshaller return marshaller def load(self, type_: Type, to_load: ExternalType): marshaller = self.get_marshaller(type_) loaded = marshaller.load(to_load) return loaded def dump(self, obj: Any, type_: Optional[Type] = None) -> ExternalType: if not type_: type_ = type(obj) marshaller = self.get_marshaller(type_) dumped = marshaller.dump(obj) return dumped def get_factories(self) -> Iterator[MarshallerFactoryABC]: return iter(self._factories)
0.883022
0.07579
from timo.database_manager.databases.mysql import MySQL import HtmlTestRunner import xmlrunner import unittest import json import os import yaml class TestMySQL(unittest.TestCase): def setUp(self): self.db = MySQL() self.db.open_DB_session() def tearDown(self): self.db.close_DB_session() def test_select_query_print(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save=None) def test_select_query_save_json(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='json') assert os.path.isfile(os.getcwd() + '/out.json') with open(file=os.getcwd() + '/out.json', mode='r', encoding='utf-8') as f: data = json.load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.json') def test_select_query_save_yaml(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='yaml') assert os.path.isfile(os.getcwd() + '/out.yaml') with open(file=os.getcwd() + '/out.yaml', mode='r', encoding='utf-8') as f: data = yaml.safe_load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.yaml') def test_select_query_save_yml(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='yml') assert os.path.isfile(os.getcwd() + '/out.yml') with open(file=os.getcwd() + '/out.yml', mode='r', encoding='utf-8') as f: data = yaml.safe_load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.yml') if __name__ == "__main__": unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='unittest-report')) # with open(file='unittest-xml-report.xml', mode='wb') as output: # unittest.main( # testRunner=xmlrunner.XMLTestRunner(output=output), # failfast=False, buffer=False, catchbreak=False # )
tests/test_mysql.py
from timo.database_manager.databases.mysql import MySQL import HtmlTestRunner import xmlrunner import unittest import json import os import yaml class TestMySQL(unittest.TestCase): def setUp(self): self.db = MySQL() self.db.open_DB_session() def tearDown(self): self.db.close_DB_session() def test_select_query_print(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save=None) def test_select_query_save_json(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='json') assert os.path.isfile(os.getcwd() + '/out.json') with open(file=os.getcwd() + '/out.json', mode='r', encoding='utf-8') as f: data = json.load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.json') def test_select_query_save_yaml(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='yaml') assert os.path.isfile(os.getcwd() + '/out.yaml') with open(file=os.getcwd() + '/out.yaml', mode='r', encoding='utf-8') as f: data = yaml.safe_load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.yaml') def test_select_query_save_yml(self): self.db.send_query(sql="SELECT MAX(BUILD_NO) FROM JENKINS_BUILD_RESULT WHERE PROJECT_NM = 'IRIS-E2E-SAAS'", type='select', save='yml') assert os.path.isfile(os.getcwd() + '/out.yml') with open(file=os.getcwd() + '/out.yml', mode='r', encoding='utf-8') as f: data = yaml.safe_load(f) assert len(data) == 1 assert type(data[0]['MAX(BUILD_NO)']) is int os.remove(os.getcwd() + '/out.yml') if __name__ == "__main__": unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='unittest-report')) # with open(file='unittest-xml-report.xml', mode='wb') as output: # unittest.main( # testRunner=xmlrunner.XMLTestRunner(output=output), # failfast=False, buffer=False, catchbreak=False # )
0.298185
0.17434
import os import numpy as np import pandas as pd from datashader.utils import lnglat_to_meters as webm from src.utils import write_log def engineer_brazilian_zip_code() -> None: """ Engineers the brazilian zip code (CEP) in the geolocation dataset by Olist. """ write_log("Reading geolocation dataset from Brazilian E-Commerce Public Dataset by Olist...") df_geolocation = read_geolocation_dataset() write_log("Successful read geolocation dataset from Brazilian E-Commerce Public Dataset by Olist.") write_log("Purging coordinates outside Brazil borders...") df_geolocation = purge_outliers(df_geolocation) write_log("Successful purged coordinates outside Brazil borders.") write_log("Extracting the zip code prefixes...") df_geolocation = get_zip_code_prefixes(df_geolocation) write_log("Successfully extracted the zip code prefixes.") write_log("Transforming coordinates to Mercator coordinates...") df_geolocation = transform_coordinates_to_mercartor_coordinates(df_geolocation) write_log("Successfully transformed coordinates to Mercator coordinates.") write_log("Converting zip codes prefixes to type int...") df_geolocation = convert_zip_code_prefix(df_geolocation) write_log("Successfully coverted zip codes prefix to type int.") write_log("Saving the engineered dataset of zip codes...") df_geolocation.to_csv("data/interim/olist_engineered_geolocation_dataset.csv", index=False) write_log("Successfully saved the engineered dataset of zip codes.") def get_zip_code_prefixes(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Gets the first three and four first digits of zip codes. """ df = df_geolocation.copy() df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix'].str[0:1] df['geolocation_zip_code_prefix_2_digits'] = df['geolocation_zip_code_prefix'].str[0:2] df['geolocation_zip_code_prefix_3_digits'] = df['geolocation_zip_code_prefix'].str[0:3] df['geolocation_zip_code_prefix_4_digits'] = df['geolocation_zip_code_prefix'].str[0:4] return df def purge_outliers(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Removes outliers. """ df = df_geolocation.copy() # Brazils most Northern spot is at 5 deg 16′ 27.8″ N lat. df = df[df["geolocation_lat"] <= 5.27438888] # Brazils most Western spot is at 73 deg, 58′ 58.19″W lng. df = df[df["geolocation_lng"] >= -73.98283055] # Brazils most southern spot is at 33 deg, 45′ 04.21″ S lat. df = df[df["geolocation_lat"] >= -33.75116944] # Brazils most Eastern spot is 34 deg, 47′ 35.33″ W lng. df = df[df["geolocation_lng"] <= -34.79314722] return df def transform_coordinates_to_mercartor_coordinates(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Transforms the latitute and longitude coordinates to Mercator x/y Coordinates. """ df = df_geolocation.copy() x, y = webm(df.geolocation_lng, df.geolocation_lat) df['x'] = pd.Series(x) df['y'] = pd.Series(y) return df def convert_zip_code_prefix(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Converts the zip code prefix into int type for plotting purposes. """ df = df_geolocation.copy() df['geolocation_zip_code_prefix'] = df['geolocation_zip_code_prefix'].astype(int) df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix_1_digits'].astype(int) df['geolocation_zip_code_prefix_2_digits'] = df['geolocation_zip_code_prefix_2_digits'].astype(int) df['geolocation_zip_code_prefix_3_digits'] = df['geolocation_zip_code_prefix_3_digits'].astype(int) df['geolocation_zip_code_prefix_4_digits'] = df['geolocation_zip_code_prefix_4_digits'].astype(int) return df def read_geolocation_dataset() -> pd.DataFrame: """ Returns the geolocation dataset from Brazilian E-Commerce Public Dataset by Olist. """ return pd.read_csv("data/raw/Brazilian_E_Commerce_Public_Dataset_by_Olist/olist_geolocation_dataset.csv",\ dtype={'geolocation_zip_code_prefix': str}) if __name__ == '__main__': engineer_brazilian_zip_code()
src/features/Engineer_Brazilian_ZIP_Code.py
import os import numpy as np import pandas as pd from datashader.utils import lnglat_to_meters as webm from src.utils import write_log def engineer_brazilian_zip_code() -> None: """ Engineers the brazilian zip code (CEP) in the geolocation dataset by Olist. """ write_log("Reading geolocation dataset from Brazilian E-Commerce Public Dataset by Olist...") df_geolocation = read_geolocation_dataset() write_log("Successful read geolocation dataset from Brazilian E-Commerce Public Dataset by Olist.") write_log("Purging coordinates outside Brazil borders...") df_geolocation = purge_outliers(df_geolocation) write_log("Successful purged coordinates outside Brazil borders.") write_log("Extracting the zip code prefixes...") df_geolocation = get_zip_code_prefixes(df_geolocation) write_log("Successfully extracted the zip code prefixes.") write_log("Transforming coordinates to Mercator coordinates...") df_geolocation = transform_coordinates_to_mercartor_coordinates(df_geolocation) write_log("Successfully transformed coordinates to Mercator coordinates.") write_log("Converting zip codes prefixes to type int...") df_geolocation = convert_zip_code_prefix(df_geolocation) write_log("Successfully coverted zip codes prefix to type int.") write_log("Saving the engineered dataset of zip codes...") df_geolocation.to_csv("data/interim/olist_engineered_geolocation_dataset.csv", index=False) write_log("Successfully saved the engineered dataset of zip codes.") def get_zip_code_prefixes(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Gets the first three and four first digits of zip codes. """ df = df_geolocation.copy() df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix'].str[0:1] df['geolocation_zip_code_prefix_2_digits'] = df['geolocation_zip_code_prefix'].str[0:2] df['geolocation_zip_code_prefix_3_digits'] = df['geolocation_zip_code_prefix'].str[0:3] df['geolocation_zip_code_prefix_4_digits'] = df['geolocation_zip_code_prefix'].str[0:4] return df def purge_outliers(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Removes outliers. """ df = df_geolocation.copy() # Brazils most Northern spot is at 5 deg 16′ 27.8″ N lat. df = df[df["geolocation_lat"] <= 5.27438888] # Brazils most Western spot is at 73 deg, 58′ 58.19″W lng. df = df[df["geolocation_lng"] >= -73.98283055] # Brazils most southern spot is at 33 deg, 45′ 04.21″ S lat. df = df[df["geolocation_lat"] >= -33.75116944] # Brazils most Eastern spot is 34 deg, 47′ 35.33″ W lng. df = df[df["geolocation_lng"] <= -34.79314722] return df def transform_coordinates_to_mercartor_coordinates(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Transforms the latitute and longitude coordinates to Mercator x/y Coordinates. """ df = df_geolocation.copy() x, y = webm(df.geolocation_lng, df.geolocation_lat) df['x'] = pd.Series(x) df['y'] = pd.Series(y) return df def convert_zip_code_prefix(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Converts the zip code prefix into int type for plotting purposes. """ df = df_geolocation.copy() df['geolocation_zip_code_prefix'] = df['geolocation_zip_code_prefix'].astype(int) df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix_1_digits'].astype(int) df['geolocation_zip_code_prefix_2_digits'] = df['geolocation_zip_code_prefix_2_digits'].astype(int) df['geolocation_zip_code_prefix_3_digits'] = df['geolocation_zip_code_prefix_3_digits'].astype(int) df['geolocation_zip_code_prefix_4_digits'] = df['geolocation_zip_code_prefix_4_digits'].astype(int) return df def read_geolocation_dataset() -> pd.DataFrame: """ Returns the geolocation dataset from Brazilian E-Commerce Public Dataset by Olist. """ return pd.read_csv("data/raw/Brazilian_E_Commerce_Public_Dataset_by_Olist/olist_geolocation_dataset.csv",\ dtype={'geolocation_zip_code_prefix': str}) if __name__ == '__main__': engineer_brazilian_zip_code()
0.655115
0.534673
from .preprocessor import FortranPreprocessor import re from .smartopen import smart_open UNIT_REGEX = re.compile(r"^\s*(?P<unit_type>module(?!\s+procedure)|program)\s*(?P<modname>\w*)", re.IGNORECASE) END_REGEX = re.compile(r"^\s*end\s*(?P<unit_type>module|program)\s*(?P<modname>\w*)?", re.IGNORECASE) USE_REGEX = re.compile(r"""^\s*use (\s*,\s*intrinsic\s*)?(\s*::\s*|\s+) # Valid separators between "use" and module name (?P<moduse>\w*) # The module name \s*(, )?\s*(only)?\s*(:)?.*?$ # Stuff that might follow the name """, re.IGNORECASE | re.VERBOSE) class FortranFile: """The modules and dependencies of a Fortran source file Args: filename (str): Source file macros (iterable): Dict of preprocessor macros to be expanded readfile (bool): Read and process the file [True] cpp_includes (list of str): List of directories to add to preprocessor search path use_preprocessor (bool): Preprocess the source file [True] """ def __init__(self, filename=None, macros=None, readfile=True, cpp_includes=None, use_preprocessor=True): self.filename = filename self.uses = None self.modules = None self.depends_on = None if readfile: with smart_open(self.filename, 'r') as f: contents = f.read() preprocessor = FortranPreprocessor() if macros: if isinstance(macros, dict): for k, v in macros.items(): preprocessor.define("{} {}".format(k, v)) else: if not isinstance(macros, list): macros = [macros] for macro in macros: if '=' in macro: temp = macro.split('=') preprocessor.define("{} {}".format(*temp)) else: preprocessor.define(macro) if cpp_includes: if not isinstance(cpp_includes, list): cpp_includes = [cpp_includes] for include_dir in cpp_includes: preprocessor.add_path(include_dir) if use_preprocessor: contents = preprocessor.parse_to_string(contents, source=self.filename) self.modules = self.get_modules(contents.splitlines()) self.uses = self.get_uses() def __str__(self): return self.filename def __repr__(self): return "FortranFile('{}')".format(self.filename) def get_modules(self, contents, macros=None): """Return all the modules or programs that are in the file Args: contents (str): Contents of the source file """ contains = {} found_units = [] starts = [] ends = [] for num, line in enumerate(contents): unit = re.match(UNIT_REGEX, line) end = re.match(END_REGEX, line) if unit: found_units.append(unit) starts.append(num) if end: ends.append(num) if found_units: if (len(found_units) != len(starts)) or (len(starts) != len(ends)): error_string = ("Unmatched start/end of modules in {} ({} begins/{} ends)" .format(self.filename, len(starts), len(ends))) raise ValueError(error_string) for unit, start, end in zip(found_units, starts, ends): name = unit.group('modname') contains[name] = FortranModule(unit_type=unit.group('unit_type'), name=name, source_file=self, text=(contents, start, end), macros=macros) # Remove duplicates before returning return contains def get_uses(self): """Return a sorted list of the modules this file USEs """ if self.modules is None: return [] # flatten list of lists return sorted(set([mod for module in self.modules.values() for mod in module.uses])) class FortranModule: """A Fortran Module or Program Args: unit_type (str): 'module' or 'program' name (str): Name of the module/program source_file (str): Name of the file containing the module/program text (tuple): Tuple containing source_file contents, and start and end lines of the module macros (dict): Any defined macros """ def __init__(self, unit_type, name, source_file=None, text=None, macros=None): self.unit_type = unit_type.strip().lower() self.name = name.strip().lower() if source_file is not None: self.source_file = source_file self.defined_at = text[1] self.end = text[2] self.uses = self.get_uses(text[0], macros) else: self.source_file = FortranFile(filename='empty', readfile=False) def __str__(self): return self.name def __repr__(self): return "FortranModule({}, '{}', '{}')".format(self.unit_type, self.name, self.source_file.filename) def get_uses(self, contents, macros=None): """Return which modules are used in the file after expanding macros Args: contents (str): Contents of the source file macros (dict): Dict of preprocessor macros to be expanded """ uses = [] for line in contents[self.defined_at:self.end]: found = re.match(USE_REGEX, line) if found: uses.append(found.group('moduse').strip()) # Remove duplicates uniq_mods = list(set(uses)) if macros is not None: for i, mod in enumerate(uniq_mods): for k, v in macros.items(): if re.match(k, mod, re.IGNORECASE): uniq_mods[i] = mod.replace(k, v) return uniq_mods
fortdepend/units.py
from .preprocessor import FortranPreprocessor import re from .smartopen import smart_open UNIT_REGEX = re.compile(r"^\s*(?P<unit_type>module(?!\s+procedure)|program)\s*(?P<modname>\w*)", re.IGNORECASE) END_REGEX = re.compile(r"^\s*end\s*(?P<unit_type>module|program)\s*(?P<modname>\w*)?", re.IGNORECASE) USE_REGEX = re.compile(r"""^\s*use (\s*,\s*intrinsic\s*)?(\s*::\s*|\s+) # Valid separators between "use" and module name (?P<moduse>\w*) # The module name \s*(, )?\s*(only)?\s*(:)?.*?$ # Stuff that might follow the name """, re.IGNORECASE | re.VERBOSE) class FortranFile: """The modules and dependencies of a Fortran source file Args: filename (str): Source file macros (iterable): Dict of preprocessor macros to be expanded readfile (bool): Read and process the file [True] cpp_includes (list of str): List of directories to add to preprocessor search path use_preprocessor (bool): Preprocess the source file [True] """ def __init__(self, filename=None, macros=None, readfile=True, cpp_includes=None, use_preprocessor=True): self.filename = filename self.uses = None self.modules = None self.depends_on = None if readfile: with smart_open(self.filename, 'r') as f: contents = f.read() preprocessor = FortranPreprocessor() if macros: if isinstance(macros, dict): for k, v in macros.items(): preprocessor.define("{} {}".format(k, v)) else: if not isinstance(macros, list): macros = [macros] for macro in macros: if '=' in macro: temp = macro.split('=') preprocessor.define("{} {}".format(*temp)) else: preprocessor.define(macro) if cpp_includes: if not isinstance(cpp_includes, list): cpp_includes = [cpp_includes] for include_dir in cpp_includes: preprocessor.add_path(include_dir) if use_preprocessor: contents = preprocessor.parse_to_string(contents, source=self.filename) self.modules = self.get_modules(contents.splitlines()) self.uses = self.get_uses() def __str__(self): return self.filename def __repr__(self): return "FortranFile('{}')".format(self.filename) def get_modules(self, contents, macros=None): """Return all the modules or programs that are in the file Args: contents (str): Contents of the source file """ contains = {} found_units = [] starts = [] ends = [] for num, line in enumerate(contents): unit = re.match(UNIT_REGEX, line) end = re.match(END_REGEX, line) if unit: found_units.append(unit) starts.append(num) if end: ends.append(num) if found_units: if (len(found_units) != len(starts)) or (len(starts) != len(ends)): error_string = ("Unmatched start/end of modules in {} ({} begins/{} ends)" .format(self.filename, len(starts), len(ends))) raise ValueError(error_string) for unit, start, end in zip(found_units, starts, ends): name = unit.group('modname') contains[name] = FortranModule(unit_type=unit.group('unit_type'), name=name, source_file=self, text=(contents, start, end), macros=macros) # Remove duplicates before returning return contains def get_uses(self): """Return a sorted list of the modules this file USEs """ if self.modules is None: return [] # flatten list of lists return sorted(set([mod for module in self.modules.values() for mod in module.uses])) class FortranModule: """A Fortran Module or Program Args: unit_type (str): 'module' or 'program' name (str): Name of the module/program source_file (str): Name of the file containing the module/program text (tuple): Tuple containing source_file contents, and start and end lines of the module macros (dict): Any defined macros """ def __init__(self, unit_type, name, source_file=None, text=None, macros=None): self.unit_type = unit_type.strip().lower() self.name = name.strip().lower() if source_file is not None: self.source_file = source_file self.defined_at = text[1] self.end = text[2] self.uses = self.get_uses(text[0], macros) else: self.source_file = FortranFile(filename='empty', readfile=False) def __str__(self): return self.name def __repr__(self): return "FortranModule({}, '{}', '{}')".format(self.unit_type, self.name, self.source_file.filename) def get_uses(self, contents, macros=None): """Return which modules are used in the file after expanding macros Args: contents (str): Contents of the source file macros (dict): Dict of preprocessor macros to be expanded """ uses = [] for line in contents[self.defined_at:self.end]: found = re.match(USE_REGEX, line) if found: uses.append(found.group('moduse').strip()) # Remove duplicates uniq_mods = list(set(uses)) if macros is not None: for i, mod in enumerate(uniq_mods): for k, v in macros.items(): if re.match(k, mod, re.IGNORECASE): uniq_mods[i] = mod.replace(k, v) return uniq_mods
0.539954
0.182316
import random from django.conf import settings from django.utils.text import slugify import factory from cms.api import add_plugin, create_page, create_title def create_i18n_page(title=None, languages=None, is_homepage=False, **kwargs): """ Creating a multilingual page is not straightforward so we should have a helper This content argument should be a dictionary with the title of the page in each language: { 'en': 'About', 'fr': 'A propos', 'de': 'Impressum', } """ template = kwargs.pop("template", None) or "richie/fullwidth.html" if title is None: # Create realistic titles in each language with faker languages = languages or [settings.LANGUAGE_CODE] i18n_titles = { language: factory.Faker("catch_phrase", locale=language).generate({}) for language in languages } elif isinstance(title, dict): # Check that the languages passed are coherent with the languages requested if any if languages: assert set(languages).issubset(title.keys()) else: languages = title.keys() i18n_titles = title elif isinstance(title, str): # Add a marker at the end of the string to differentiate each language languages = languages or [settings.LANGUAGE_CODE] i18n_titles = { language: "{title:s} {language:s}".format(title=title, language=language) for language in languages } else: raise ValueError( "Title should be a string or a dictionary of language/string pairs" ) # Assert that the languages passed are declared in settings assert set(languages).issubset({l[0] for l in settings.LANGUAGES}) # Make a copy of languages to avoid muting it in what follows languages = list(languages) # Create the page with a first language from what is given to us first_language = languages.pop(0) slug = slugify(i18n_titles[first_language]) page = create_page( language=first_language, menu_title=i18n_titles[first_language], title=i18n_titles[first_language], slug=slug, template=template, **kwargs ) if is_homepage is True: page.set_as_homepage() # Add a title for each additional language for language in languages: create_title( language=language, menu_title=i18n_titles[language], title=i18n_titles[language], slug=slugify(i18n_titles[language]), page=page, ) # Publish page in each additional language if kwargs.get("published") is True: page.publish(language) return page # pylint: disable=too-many-arguments def create_text_plugin( page, slot, languages=None, is_html=True, max_nb_chars=None, nb_paragraphs=None, plugin_type="CKEditorPlugin", ): """ A common function to create and add a text plugin of any type instance to a placeholder filled with some random text using Faker. Arguments: page (cms.models.pagemodel.Page): Instance of a Page used to search for given slot (aka a placeholder name). slot (string): A placeholder name available from page template. Keyword Arguments: languages (iterable): An iterable yielding language codes for which a text plugin should be created. If ``None`` (default) it uses the default language from settings. is_html (boolean): If True, every paragraph will be surrounded with an HTML paragraph markup. Default is True. max_nb_chars (integer): Number of characters limit to create each paragraph. Default is None so a random number between 200 and 400 will be used at each paragraph. nb_paragraphs (integer): Number of paragraphs to create in content. Default is None so a random number between 2 and 4 will be used. plugin_type (string or object): Type of plugin. Default use CKEditorPlugin but you can use any other similar plugin that has a body attribute. Returns: object: Created plugin instance. """ languages = languages or [settings.LANGUAGE_CODE] container = "<p>{:s}</p>" if is_html else "{:s}" nb_paragraphs = nb_paragraphs or random.randint(2, 4) placeholder = page.placeholders.get(slot=slot) for language in languages: paragraphs = [] for _ in range(nb_paragraphs): max_nb_chars = max_nb_chars or random.randint(200, 400) paragraphs.append( factory.Faker( "text", max_nb_chars=max_nb_chars, locale=language ).generate({}) ) body = [container.format(p) for p in paragraphs] add_plugin( language=language, placeholder=placeholder, plugin_type=plugin_type, body="".join(body), ) def recursive_page_creation(site, pages, parent=None): """ Recursively create page following tree structure with parent/children. Arguments: site (django.contrib.sites.models.Site): Site object which page will be linked to. pages (dict): Page items to create recursively such as 'children' key value can be a dict to create child pages. The current page is given to children for parent relation. Keyword Arguments: parent (cms.models.pagemodel.Page): Page used as a parent to create page item from `pages` argument. Returns: dict: Created page items. """ pages_created = {} for name, info in pages.items(): page = create_i18n_page( info["content"], is_homepage=(name == "home"), in_navigation=info["in_navigation"], published=True, site=site, parent=parent, **info["kwargs"] ) pages_created[name] = page # Create children if info.get("children", None): pages_created[name].created_children = recursive_page_creation( site, info["children"], parent=page ) return pages_created
src/richie/apps/core/helpers.py
import random from django.conf import settings from django.utils.text import slugify import factory from cms.api import add_plugin, create_page, create_title def create_i18n_page(title=None, languages=None, is_homepage=False, **kwargs): """ Creating a multilingual page is not straightforward so we should have a helper This content argument should be a dictionary with the title of the page in each language: { 'en': 'About', 'fr': 'A propos', 'de': 'Impressum', } """ template = kwargs.pop("template", None) or "richie/fullwidth.html" if title is None: # Create realistic titles in each language with faker languages = languages or [settings.LANGUAGE_CODE] i18n_titles = { language: factory.Faker("catch_phrase", locale=language).generate({}) for language in languages } elif isinstance(title, dict): # Check that the languages passed are coherent with the languages requested if any if languages: assert set(languages).issubset(title.keys()) else: languages = title.keys() i18n_titles = title elif isinstance(title, str): # Add a marker at the end of the string to differentiate each language languages = languages or [settings.LANGUAGE_CODE] i18n_titles = { language: "{title:s} {language:s}".format(title=title, language=language) for language in languages } else: raise ValueError( "Title should be a string or a dictionary of language/string pairs" ) # Assert that the languages passed are declared in settings assert set(languages).issubset({l[0] for l in settings.LANGUAGES}) # Make a copy of languages to avoid muting it in what follows languages = list(languages) # Create the page with a first language from what is given to us first_language = languages.pop(0) slug = slugify(i18n_titles[first_language]) page = create_page( language=first_language, menu_title=i18n_titles[first_language], title=i18n_titles[first_language], slug=slug, template=template, **kwargs ) if is_homepage is True: page.set_as_homepage() # Add a title for each additional language for language in languages: create_title( language=language, menu_title=i18n_titles[language], title=i18n_titles[language], slug=slugify(i18n_titles[language]), page=page, ) # Publish page in each additional language if kwargs.get("published") is True: page.publish(language) return page # pylint: disable=too-many-arguments def create_text_plugin( page, slot, languages=None, is_html=True, max_nb_chars=None, nb_paragraphs=None, plugin_type="CKEditorPlugin", ): """ A common function to create and add a text plugin of any type instance to a placeholder filled with some random text using Faker. Arguments: page (cms.models.pagemodel.Page): Instance of a Page used to search for given slot (aka a placeholder name). slot (string): A placeholder name available from page template. Keyword Arguments: languages (iterable): An iterable yielding language codes for which a text plugin should be created. If ``None`` (default) it uses the default language from settings. is_html (boolean): If True, every paragraph will be surrounded with an HTML paragraph markup. Default is True. max_nb_chars (integer): Number of characters limit to create each paragraph. Default is None so a random number between 200 and 400 will be used at each paragraph. nb_paragraphs (integer): Number of paragraphs to create in content. Default is None so a random number between 2 and 4 will be used. plugin_type (string or object): Type of plugin. Default use CKEditorPlugin but you can use any other similar plugin that has a body attribute. Returns: object: Created plugin instance. """ languages = languages or [settings.LANGUAGE_CODE] container = "<p>{:s}</p>" if is_html else "{:s}" nb_paragraphs = nb_paragraphs or random.randint(2, 4) placeholder = page.placeholders.get(slot=slot) for language in languages: paragraphs = [] for _ in range(nb_paragraphs): max_nb_chars = max_nb_chars or random.randint(200, 400) paragraphs.append( factory.Faker( "text", max_nb_chars=max_nb_chars, locale=language ).generate({}) ) body = [container.format(p) for p in paragraphs] add_plugin( language=language, placeholder=placeholder, plugin_type=plugin_type, body="".join(body), ) def recursive_page_creation(site, pages, parent=None): """ Recursively create page following tree structure with parent/children. Arguments: site (django.contrib.sites.models.Site): Site object which page will be linked to. pages (dict): Page items to create recursively such as 'children' key value can be a dict to create child pages. The current page is given to children for parent relation. Keyword Arguments: parent (cms.models.pagemodel.Page): Page used as a parent to create page item from `pages` argument. Returns: dict: Created page items. """ pages_created = {} for name, info in pages.items(): page = create_i18n_page( info["content"], is_homepage=(name == "home"), in_navigation=info["in_navigation"], published=True, site=site, parent=parent, **info["kwargs"] ) pages_created[name] = page # Create children if info.get("children", None): pages_created[name].created_children = recursive_page_creation( site, info["children"], parent=page ) return pages_created
0.694303
0.33497
import MySQLdb import time import re import os import urllib from datetime import datetime from xml.sax.saxutils import unescape f = open('workfile.tex', 'w') def db(hst, usr, pw, dba): db = MySQLdb.connect(host=hst, user=usr, passwd=pw, db=dba) # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT `id`, `title`, `body`, `timestamp` as `date` FROM `entries` WHERE isdraft = 'false' ORDER BY timestamp ASC") years = {} # ([],[],[],[],[],[],[],[],[],[],[],[]) # print all the first cell of all the rows for row in cur.fetchall(): if len(row) >= 4: dt_obj = datetime.fromtimestamp(row[3]) if repr(dt_obj.year) not in years: years[repr(dt_obj.year)] = ([],[],[],[],[],[],[],[],[],[],[],[]) title = row[1].decode('iso-8859-1') body = row[2].decode('iso-8859-1') # translation table for Umlaut table = { ord(u'$'): u'\$', ord(u'"'): u'"{}', ord(u'ä'): u'{\\\"a}', ord(u'ö'): u'{\\\"o}', ord(u'ü'): u'{\\\"u}', ord(u'Ä'): u'{\\\"A}', ord(u'Ö'): u'{\\\"O}', ord(u'Ü'): u'{\\\"U}', ord(u'ß'): u'{\\ss}', ord(u'%'): u'\\%', ord(u'†'): u'\\textdied', ord(u'‡'): u'\\ddag', ord(u'†'): u'\\textdagger', ord(u'_'): u'\_', } title = title.translate(table) body = body.translate(table) title = re.sub(r'[^\x00-\x7F]','', title) body = re.sub(r'[^\x00-\x7F]','', body) title = title.encode('utf-8') body = body.encode('utf-8') years[repr(dt_obj.year)][dt_obj.month-1].append((row[0], title, body, row[3])) db.close() year(years) f.close def year(years): for key in sorted(years.keys()): (jan,feb,mar,apr,mai,jun,jul,aug,sep,okt,nov,dez) = years[key] # print years if len(jan)+len(feb)+len(mar)+len(apr)+len(mai)+len(jun)+len(jul)+len(aug)+len(sep)+len(okt)+len(nov)+len(dez) > 0: f.write("\chapter{"+ key + "}\n") # print months if len(jan) > 0: f.write("\section{Januar " + key + "}\n") month(jan) if len(feb) > 0: f.write("\section{Februar " + key + "}\n") month(feb) if len(mar) > 0: f.write("\section{M{\\\"a}rz " + key + "}\n") month(mar) if len(apr) > 0: f.write("\section{April " + key + "}\n") month(apr) if len(mai) > 0: f.write("\section{Mai " + key + "}\n") month(mai) if len(jun) > 0: f.write("\section{Juni " + key + "}\n") month(jun) if len(jul) > 0: f.write("\section{Juli " + key + "}\n") month(jul) if len(aug) > 0: f.write("\section{August " + key + "}\n") month(aug) if len(sep) > 0: f.write("\section{September " + key + "}\n") month(sep) if len(okt) > 0: f.write("\section{Oktober " + key + "}\n") month(okt) if len(nov) > 0: f.write("\section{November " + key + "}\n") month(jan) if len(nov) > 0: f.write("\section{Dezember " + key + "}\n") month(dez) f.write("\n\n\n\\clearpage") def month(month): for (id, title, body, timestamp) in month: f.write("\subsection{" + title + "}\n") f.write(bodyCleaning(body, title)+"\n\n") def bodyCleaning(body, title): img = re.compile('<img src="{}([^"]+)"') cleanedBody = body for tag in img.finditer(cleanedBody): cleanedURL = tag.group(1).replace('{}','').replace("\_","_").replace("\%","%") # print title + ": " + cleanedURL urllib.urlretrieve(cleanedURL, "images/" + os.path.basename(cleanedURL)) if os.path.splitext(cleanedURL)[1] != ".gif": escapedURL = cleanedURL.replace("_","\_").replace("%","\%") cleanedBody = re.sub('<img src="{}([^"]+)"[{}\s]* />', "\n\n \\begin{figure}[ht]\\centering\\href{" + escapedURL + "}{\\includegraphics[width=1.0 \\textwidth]{" + "images/" + os.path.basename(escapedURL.replace("%","\%")) + "}}\\caption{" + title + "}\\end{figure}\n\n", body, 1) ahref = re.compile('<a href="([^"]+)"') for tag in ahref.finditer(cleanedBody): cleanedURL = tag.group(1).replace('{}','') print title + ": " + cleanedURL cleanedBody = cleanedBody + "\n \\\\ \\href{" + cleanedURL + "}{Link}" cleanedBody = re.sub('<[^<]+?>', '', cleanedBody) html_escape_table = { "&amp;":"\&", "&quot;":'"{}', "&apos;":'"{}', "&gt;":">", "&lt;":"<", "&nbsp;":" ", "&#699;":"'", "&#31069;":"",#祝 "&#25105;":"",#我 "&#22909;":"",#好 "&#36816;":"",#运 } cleanedBody = unescape(cleanedBody, html_escape_table) return cleanedBody db()
db.py
import MySQLdb import time import re import os import urllib from datetime import datetime from xml.sax.saxutils import unescape f = open('workfile.tex', 'w') def db(hst, usr, pw, dba): db = MySQLdb.connect(host=hst, user=usr, passwd=pw, db=dba) # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT `id`, `title`, `body`, `timestamp` as `date` FROM `entries` WHERE isdraft = 'false' ORDER BY timestamp ASC") years = {} # ([],[],[],[],[],[],[],[],[],[],[],[]) # print all the first cell of all the rows for row in cur.fetchall(): if len(row) >= 4: dt_obj = datetime.fromtimestamp(row[3]) if repr(dt_obj.year) not in years: years[repr(dt_obj.year)] = ([],[],[],[],[],[],[],[],[],[],[],[]) title = row[1].decode('iso-8859-1') body = row[2].decode('iso-8859-1') # translation table for Umlaut table = { ord(u'$'): u'\$', ord(u'"'): u'"{}', ord(u'ä'): u'{\\\"a}', ord(u'ö'): u'{\\\"o}', ord(u'ü'): u'{\\\"u}', ord(u'Ä'): u'{\\\"A}', ord(u'Ö'): u'{\\\"O}', ord(u'Ü'): u'{\\\"U}', ord(u'ß'): u'{\\ss}', ord(u'%'): u'\\%', ord(u'†'): u'\\textdied', ord(u'‡'): u'\\ddag', ord(u'†'): u'\\textdagger', ord(u'_'): u'\_', } title = title.translate(table) body = body.translate(table) title = re.sub(r'[^\x00-\x7F]','', title) body = re.sub(r'[^\x00-\x7F]','', body) title = title.encode('utf-8') body = body.encode('utf-8') years[repr(dt_obj.year)][dt_obj.month-1].append((row[0], title, body, row[3])) db.close() year(years) f.close def year(years): for key in sorted(years.keys()): (jan,feb,mar,apr,mai,jun,jul,aug,sep,okt,nov,dez) = years[key] # print years if len(jan)+len(feb)+len(mar)+len(apr)+len(mai)+len(jun)+len(jul)+len(aug)+len(sep)+len(okt)+len(nov)+len(dez) > 0: f.write("\chapter{"+ key + "}\n") # print months if len(jan) > 0: f.write("\section{Januar " + key + "}\n") month(jan) if len(feb) > 0: f.write("\section{Februar " + key + "}\n") month(feb) if len(mar) > 0: f.write("\section{M{\\\"a}rz " + key + "}\n") month(mar) if len(apr) > 0: f.write("\section{April " + key + "}\n") month(apr) if len(mai) > 0: f.write("\section{Mai " + key + "}\n") month(mai) if len(jun) > 0: f.write("\section{Juni " + key + "}\n") month(jun) if len(jul) > 0: f.write("\section{Juli " + key + "}\n") month(jul) if len(aug) > 0: f.write("\section{August " + key + "}\n") month(aug) if len(sep) > 0: f.write("\section{September " + key + "}\n") month(sep) if len(okt) > 0: f.write("\section{Oktober " + key + "}\n") month(okt) if len(nov) > 0: f.write("\section{November " + key + "}\n") month(jan) if len(nov) > 0: f.write("\section{Dezember " + key + "}\n") month(dez) f.write("\n\n\n\\clearpage") def month(month): for (id, title, body, timestamp) in month: f.write("\subsection{" + title + "}\n") f.write(bodyCleaning(body, title)+"\n\n") def bodyCleaning(body, title): img = re.compile('<img src="{}([^"]+)"') cleanedBody = body for tag in img.finditer(cleanedBody): cleanedURL = tag.group(1).replace('{}','').replace("\_","_").replace("\%","%") # print title + ": " + cleanedURL urllib.urlretrieve(cleanedURL, "images/" + os.path.basename(cleanedURL)) if os.path.splitext(cleanedURL)[1] != ".gif": escapedURL = cleanedURL.replace("_","\_").replace("%","\%") cleanedBody = re.sub('<img src="{}([^"]+)"[{}\s]* />', "\n\n \\begin{figure}[ht]\\centering\\href{" + escapedURL + "}{\\includegraphics[width=1.0 \\textwidth]{" + "images/" + os.path.basename(escapedURL.replace("%","\%")) + "}}\\caption{" + title + "}\\end{figure}\n\n", body, 1) ahref = re.compile('<a href="([^"]+)"') for tag in ahref.finditer(cleanedBody): cleanedURL = tag.group(1).replace('{}','') print title + ": " + cleanedURL cleanedBody = cleanedBody + "\n \\\\ \\href{" + cleanedURL + "}{Link}" cleanedBody = re.sub('<[^<]+?>', '', cleanedBody) html_escape_table = { "&amp;":"\&", "&quot;":'"{}', "&apos;":'"{}', "&gt;":">", "&lt;":"<", "&nbsp;":" ", "&#699;":"'", "&#31069;":"",#祝 "&#25105;":"",#我 "&#22909;":"",#好 "&#36816;":"",#运 } cleanedBody = unescape(cleanedBody, html_escape_table) return cleanedBody db()
0.164315
0.088939
import uuid from dashboards.models import Dashboard, DashboardWidget, DashboardRow from exceptions import InvalidDashboardParametersException class DashboardFactory(object): @staticmethod def create_dashboard_from_query_params(query_params): dashboard = Dashboard() dashboard.name = query_params['name'] dashboard.description = query_params['description'] dashboard.template = query_params['template'] dashboard.monitored_object_id = query_params['monitored-object-uuid'] dashboard.transmitter_id = query_params['transmitter-uuid'] dashboard.uuid = uuid.uuid4() for widget in DashboardFactory.__get_default_widgets_for(template=query_params['template']): dashboard.widgets.append(widget) return dashboard @staticmethod def __get_default_widgets_for(template): widgets = [] if template == Dashboard.TEMPLATES['aircraft']: widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['altimeter'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['variometer'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['heading'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['airspeed'])) return widgets class DashboardWidgetFactory(object): DEFAULT_GAUGE_SIZE = 2 DEFAULT_CHART_SIZE = 5 DEFAULT_ALTITUDE_GAUGE_POSITION = 0 DEFAULT_VERTICAL_SPEED_GAUGE_POSITION = 1 DEFAULT_HEADING_INDICATOR_POSITION = 2 DEFAULT_AIR_SPEED_GAUGE_POSITION = 3 @staticmethod def create_default_widget_from(widget_type): widget = DashboardWidget() if widget_type is DashboardWidget.TYPES['variometer']: widget.name = "Vertical speed" widget.description = "The vertical speed gauge(variometer) inform of the rate of descent or climb" widget.measure_units = DashboardWidget.MEASURE_UNITS['ft/min'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_VERTICAL_SPEED_GAUGE_POSITION widget.type = DashboardWidget.TYPES['variometer'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['airspeed']: widget.name = "Air speed" widget.description = "The airspeed indicator or airspeed gauge is an instrument used in an aircraft to " \ "display the craft's airspeed, typically in knots" widget.measure_units = DashboardWidget.MEASURE_UNITS['kn'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_AIR_SPEED_GAUGE_POSITION widget.type = DashboardWidget.TYPES['airspeed'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['altimeter']: widget.name = "Altitude" widget.description = "An altimeter or an altitude meter is an instrument used to measure the altitude" \ " of an object above a fixed level." widget.measure_units = DashboardWidget.MEASURE_UNITS['ft'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_ALTITUDE_GAUGE_POSITION widget.type = DashboardWidget.TYPES['altimeter'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['heading']: widget.name = "Heading" widget.description = "The heading indicator (also called an HI) is a flight instrument used in an" \ " aircraft to inform the pilot of the aircraft's heading." widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_HEADING_INDICATOR_POSITION widget.type = DashboardWidget.TYPES['heading'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['line-chart']: widget.name = "Chart" widget.description = "A line chart or line graph is a type of chart which displays information as a" \ " series of data points called 'markers' connected by straight line segments." widget.width = DashboardWidgetFactory.DEFAULT_CHART_SIZE widget.type = DashboardWidget.TYPES['line-chart'] widget.category = DashboardWidget.CATEGORIES['chart'] widget.uuid = uuid.uuid4() else: raise InvalidDashboardParametersException("The provided dashboard widget type is invalid") return widget @staticmethod def create_widget_from_query_params(query_params): widget = DashboardWidget() widget.name = query_params['name'] widget.description = query_params['description'] widget.measure_units = DashboardWidget.MEASURE_UNITS[query_params['measure-units']] widget.width = int(query_params['width']) widget.grid_position = 0 widget.type = query_params['type'] widget.category = DashboardWidget.TYPES_TO_CATEGORY[query_params['type']] widget.uuid = uuid.uuid4() widget.sensor_id = query_params['sensor'] widget.sensor_measure = query_params['sensor-measure'] if widget.type == DashboardWidget.TYPES['gauge']: widget.minValue = float(query_params['minimum-value']) widget.maxValue = float(query_params['maximum-value']) return widget class DashboardRowsFactory(object): @staticmethod def create_dashboard_rows_from(widgets): dashboard_rows = [] dashboard_row = DashboardRow() for widget in widgets: if dashboard_row.has_room_for(widget): dashboard_row.add_widget(widget) else: dashboard_rows.append(dashboard_row) dashboard_row = DashboardRow() dashboard_row.add_widget(widget) dashboard_rows.append(dashboard_row) return dashboard_rows
dashboards/factories.py
import uuid from dashboards.models import Dashboard, DashboardWidget, DashboardRow from exceptions import InvalidDashboardParametersException class DashboardFactory(object): @staticmethod def create_dashboard_from_query_params(query_params): dashboard = Dashboard() dashboard.name = query_params['name'] dashboard.description = query_params['description'] dashboard.template = query_params['template'] dashboard.monitored_object_id = query_params['monitored-object-uuid'] dashboard.transmitter_id = query_params['transmitter-uuid'] dashboard.uuid = uuid.uuid4() for widget in DashboardFactory.__get_default_widgets_for(template=query_params['template']): dashboard.widgets.append(widget) return dashboard @staticmethod def __get_default_widgets_for(template): widgets = [] if template == Dashboard.TEMPLATES['aircraft']: widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['altimeter'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['variometer'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['heading'])) widgets.append(DashboardWidgetFactory.create_default_widget_from( widget_type=DashboardWidget.TYPES['airspeed'])) return widgets class DashboardWidgetFactory(object): DEFAULT_GAUGE_SIZE = 2 DEFAULT_CHART_SIZE = 5 DEFAULT_ALTITUDE_GAUGE_POSITION = 0 DEFAULT_VERTICAL_SPEED_GAUGE_POSITION = 1 DEFAULT_HEADING_INDICATOR_POSITION = 2 DEFAULT_AIR_SPEED_GAUGE_POSITION = 3 @staticmethod def create_default_widget_from(widget_type): widget = DashboardWidget() if widget_type is DashboardWidget.TYPES['variometer']: widget.name = "Vertical speed" widget.description = "The vertical speed gauge(variometer) inform of the rate of descent or climb" widget.measure_units = DashboardWidget.MEASURE_UNITS['ft/min'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_VERTICAL_SPEED_GAUGE_POSITION widget.type = DashboardWidget.TYPES['variometer'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['airspeed']: widget.name = "Air speed" widget.description = "The airspeed indicator or airspeed gauge is an instrument used in an aircraft to " \ "display the craft's airspeed, typically in knots" widget.measure_units = DashboardWidget.MEASURE_UNITS['kn'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_AIR_SPEED_GAUGE_POSITION widget.type = DashboardWidget.TYPES['airspeed'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['altimeter']: widget.name = "Altitude" widget.description = "An altimeter or an altitude meter is an instrument used to measure the altitude" \ " of an object above a fixed level." widget.measure_units = DashboardWidget.MEASURE_UNITS['ft'] widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_ALTITUDE_GAUGE_POSITION widget.type = DashboardWidget.TYPES['altimeter'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['heading']: widget.name = "Heading" widget.description = "The heading indicator (also called an HI) is a flight instrument used in an" \ " aircraft to inform the pilot of the aircraft's heading." widget.width = DashboardWidgetFactory.DEFAULT_GAUGE_SIZE widget.grid_position = DashboardWidgetFactory.DEFAULT_HEADING_INDICATOR_POSITION widget.type = DashboardWidget.TYPES['heading'] widget.category = DashboardWidget.CATEGORIES['gauge'] widget.uuid = uuid.uuid4() elif widget_type is DashboardWidget.TYPES['line-chart']: widget.name = "Chart" widget.description = "A line chart or line graph is a type of chart which displays information as a" \ " series of data points called 'markers' connected by straight line segments." widget.width = DashboardWidgetFactory.DEFAULT_CHART_SIZE widget.type = DashboardWidget.TYPES['line-chart'] widget.category = DashboardWidget.CATEGORIES['chart'] widget.uuid = uuid.uuid4() else: raise InvalidDashboardParametersException("The provided dashboard widget type is invalid") return widget @staticmethod def create_widget_from_query_params(query_params): widget = DashboardWidget() widget.name = query_params['name'] widget.description = query_params['description'] widget.measure_units = DashboardWidget.MEASURE_UNITS[query_params['measure-units']] widget.width = int(query_params['width']) widget.grid_position = 0 widget.type = query_params['type'] widget.category = DashboardWidget.TYPES_TO_CATEGORY[query_params['type']] widget.uuid = uuid.uuid4() widget.sensor_id = query_params['sensor'] widget.sensor_measure = query_params['sensor-measure'] if widget.type == DashboardWidget.TYPES['gauge']: widget.minValue = float(query_params['minimum-value']) widget.maxValue = float(query_params['maximum-value']) return widget class DashboardRowsFactory(object): @staticmethod def create_dashboard_rows_from(widgets): dashboard_rows = [] dashboard_row = DashboardRow() for widget in widgets: if dashboard_row.has_room_for(widget): dashboard_row.add_widget(widget) else: dashboard_rows.append(dashboard_row) dashboard_row = DashboardRow() dashboard_row.add_widget(widget) dashboard_rows.append(dashboard_row) return dashboard_rows
0.667364
0.110615
see: http://www.astroml.org/book_figures/chapter3/fig_bivariate_gaussian.html ''' import numpy as np from matplotlib import pyplot as plt from matplotlib.patches import Ellipse from astroML.stats.random import bivariate_normal from astroML.plotting import setup_text_plots from IPython.display import SVG,display import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm import math import matplotlib.lines as lines import matplotlib.patches as patches from sklearn.mixture import GaussianMixture from scipy import stats import scipy from scipy.optimize import curve_fit from scipy.misc import factorial import pandas as pd from scipy.optimize import minimize class ForestPreprocessing(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.filepath="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv" self.filepath010="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.010.datefixed.csv" self.filepath020="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.020.month.poissoncounters.csv" self.filepath030="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.030.weekday.poissoncounters.csv" self.df = pd.read_csv(self.filepath, delimiter=';') self.months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'] self.wdays = ['mon','tue','wed','thu','fri','sat','sun'] ## test numerical approximation close to analytical one def test01DummyRead(self): pass print (self.df) def test02CheckMissingValues(self): pass print (self.df.isnull().values.sum()) # approximate to gaussian distribution for the generated data set. def test03MakeDateNumeric(self): #df2 = (self.df['month'] == 'oct') for month_ in self.months: self.df.month[self.df.month==month_] = self.months.index(month_)+1 for wday_ in self.wdays: self.df.day[self.df.day==wday_] = self.wdays.index(wday_)+1 self.df.to_csv(self.filepath010, sep=';',index= False) print (self.df) pass def test04AddMonthPoissonCounters(self): self.df = pd.read_csv(self.filepath010, delimiter=';') monthcounts = self.df['month'].value_counts() self.df['month_firecount'] = 1 for idx,item in monthcounts.iteritems(): self.df.month_firecount[self.df.month==idx]=item self.df.to_csv(self.filepath020, sep=';',index= False) def test05AddWeeklyPoissonCounters(self): self.df = pd.read_csv(self.filepath020, delimiter=';') daycounts = self.df['day'].value_counts() print (daycounts) self.df['weekday_firecount'] = 1 for idx,item in daycounts.iteritems(): self.df.weekday_firecount[self.df.day==idx]=item self.df.to_csv(self.filepath030, sep=';',index= False) def poissonParam1(self, data_): min_=np.min(data_) if min_<0: min_=0 RANGE = [min_, np.sum(data_)+1] print ("range", RANGE) # the bins should be of integer width, because poisson is an integer distribution entries, bin_edges, patches = plt.hist(data_, bins=30, range=RANGE, normed=True) # calculate binmiddles bin_middles = 0.5*(bin_edges[1:] + bin_edges[:-1]) # poisson function, parameter lamb is the fit parameter def poisson(k, lamb): return (lamb**k/factorial(k)) * np.exp(-lamb) # fit with curve_fit parameters, cov_matrix = curve_fit(poisson, bin_middles, entries) return parameters[0] def poissonParam2(self, data_): # poisson function, parameter lamb is the fit parameter def poisson(k, lamb): """poisson pdf, parameter lamb is the fit parameter""" return (lamb**k/factorial(k)) * np.exp(-lamb) def negLogLikelihood(params, data): """ the negative log-Likelohood-Function""" lnl = - np.sum(np.log(poisson(data, params[0]))) return lnl result = minimize(negLogLikelihood, # function to minimize x0=np.ones(1), # start value args=(data_,), # additional arguments for function method='Powell', # minimization method, see docs ) # fit with curve_fit, result.x = poisson_lambda return result.x def test06EstimateLambdaOfMonthlyPoisson(self): self.df = pd.read_csv(self.filepath030, delimiter=';') monthIndices = np.arange(1,len(self.months)+1) DATA_SIZE = 12 #len(monthIndices) month_firecounts = [] for i in monthIndices: firecount = self.df.month_firecount[self.df.month==i].iloc[0] month_firecounts.append(firecount) #zeroth month has this firecount month_firecounts = np.sort(month_firecounts, axis=0) print (month_firecounts) #print (np.sort(np.unique(month_firecounts))) synthetic_data= np.random.poisson(np.sum(month_firecounts)/DATA_SIZE, DATA_SIZE) data = month_firecounts #data = synthetic_data lambda_ = self.poissonParam2(data ) print ("poisson.lambda",lambda_) predicted = stats.poisson.rvs(lambda_, size=DATA_SIZE) print (np.sum(data)) print (np.sum(predicted)) def start(self): pass #self.test01DummyRead() #self.test02CheckMissingValues() # self.test03MakeDateNumeric() # self.test04AddMonthPoissonCounters() # self.test05AddWeeklyPoissonCounters() self.test06EstimateLambdaOfMonthlyPoisson() np.random.seed(2018) mmp = ForestPreprocessing() mmp.start()
second-round-intreview/parcoord-brushing/backend/src/paper2declutter/preprocessing/ForestPreprocesing.py
see: http://www.astroml.org/book_figures/chapter3/fig_bivariate_gaussian.html ''' import numpy as np from matplotlib import pyplot as plt from matplotlib.patches import Ellipse from astroML.stats.random import bivariate_normal from astroML.plotting import setup_text_plots from IPython.display import SVG,display import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm import math import matplotlib.lines as lines import matplotlib.patches as patches from sklearn.mixture import GaussianMixture from scipy import stats import scipy from scipy.optimize import curve_fit from scipy.misc import factorial import pandas as pd from scipy.optimize import minimize class ForestPreprocessing(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.filepath="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv" self.filepath010="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.010.datefixed.csv" self.filepath020="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.020.month.poissoncounters.csv" self.filepath030="/Users/halil/Yandex.Disk.localized/root/academic/myphd/phd/0070-coding/declutter-pc-temporal/backend/src/data/forestfires.csv.030.weekday.poissoncounters.csv" self.df = pd.read_csv(self.filepath, delimiter=';') self.months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'] self.wdays = ['mon','tue','wed','thu','fri','sat','sun'] ## test numerical approximation close to analytical one def test01DummyRead(self): pass print (self.df) def test02CheckMissingValues(self): pass print (self.df.isnull().values.sum()) # approximate to gaussian distribution for the generated data set. def test03MakeDateNumeric(self): #df2 = (self.df['month'] == 'oct') for month_ in self.months: self.df.month[self.df.month==month_] = self.months.index(month_)+1 for wday_ in self.wdays: self.df.day[self.df.day==wday_] = self.wdays.index(wday_)+1 self.df.to_csv(self.filepath010, sep=';',index= False) print (self.df) pass def test04AddMonthPoissonCounters(self): self.df = pd.read_csv(self.filepath010, delimiter=';') monthcounts = self.df['month'].value_counts() self.df['month_firecount'] = 1 for idx,item in monthcounts.iteritems(): self.df.month_firecount[self.df.month==idx]=item self.df.to_csv(self.filepath020, sep=';',index= False) def test05AddWeeklyPoissonCounters(self): self.df = pd.read_csv(self.filepath020, delimiter=';') daycounts = self.df['day'].value_counts() print (daycounts) self.df['weekday_firecount'] = 1 for idx,item in daycounts.iteritems(): self.df.weekday_firecount[self.df.day==idx]=item self.df.to_csv(self.filepath030, sep=';',index= False) def poissonParam1(self, data_): min_=np.min(data_) if min_<0: min_=0 RANGE = [min_, np.sum(data_)+1] print ("range", RANGE) # the bins should be of integer width, because poisson is an integer distribution entries, bin_edges, patches = plt.hist(data_, bins=30, range=RANGE, normed=True) # calculate binmiddles bin_middles = 0.5*(bin_edges[1:] + bin_edges[:-1]) # poisson function, parameter lamb is the fit parameter def poisson(k, lamb): return (lamb**k/factorial(k)) * np.exp(-lamb) # fit with curve_fit parameters, cov_matrix = curve_fit(poisson, bin_middles, entries) return parameters[0] def poissonParam2(self, data_): # poisson function, parameter lamb is the fit parameter def poisson(k, lamb): """poisson pdf, parameter lamb is the fit parameter""" return (lamb**k/factorial(k)) * np.exp(-lamb) def negLogLikelihood(params, data): """ the negative log-Likelohood-Function""" lnl = - np.sum(np.log(poisson(data, params[0]))) return lnl result = minimize(negLogLikelihood, # function to minimize x0=np.ones(1), # start value args=(data_,), # additional arguments for function method='Powell', # minimization method, see docs ) # fit with curve_fit, result.x = poisson_lambda return result.x def test06EstimateLambdaOfMonthlyPoisson(self): self.df = pd.read_csv(self.filepath030, delimiter=';') monthIndices = np.arange(1,len(self.months)+1) DATA_SIZE = 12 #len(monthIndices) month_firecounts = [] for i in monthIndices: firecount = self.df.month_firecount[self.df.month==i].iloc[0] month_firecounts.append(firecount) #zeroth month has this firecount month_firecounts = np.sort(month_firecounts, axis=0) print (month_firecounts) #print (np.sort(np.unique(month_firecounts))) synthetic_data= np.random.poisson(np.sum(month_firecounts)/DATA_SIZE, DATA_SIZE) data = month_firecounts #data = synthetic_data lambda_ = self.poissonParam2(data ) print ("poisson.lambda",lambda_) predicted = stats.poisson.rvs(lambda_, size=DATA_SIZE) print (np.sum(data)) print (np.sum(predicted)) def start(self): pass #self.test01DummyRead() #self.test02CheckMissingValues() # self.test03MakeDateNumeric() # self.test04AddMonthPoissonCounters() # self.test05AddWeeklyPoissonCounters() self.test06EstimateLambdaOfMonthlyPoisson() np.random.seed(2018) mmp = ForestPreprocessing() mmp.start()
0.424173
0.45042
import re from lib.nlp import helper OFFSET_OF_NEXT_WORD = 2 BRACKET_MAP_OPEN = {'[': ']', '(': ')', '{': '}'} BRACKET_MAP_CLOSE = {']': '[', ')': '(', '}': '{'} TAILING_CHARS = [':', ';', '?', '!', ','] def sent_tokenize(text): ''' Sentence segmentation with user specific algorithm. NOTE: It's might be better for bioinformatics publication only. ''' text = helper.remove_newline(text) text = helper.optimize_space(text) sent_list = [] sent_buf = [] word_buf = [] bracket_stack = [] in_bracket = False text_len = len(text) max_index = text_len - 1 for i in range(text_len): cur_char = text[i] if i == max_index: sent_buf.append(''.join(word_buf) + cur_char) sent_list.append(helper.optimize_space(' '.join(sent_buf))) word_buf = [] sent_buf = [] break if cur_char == ' ': sent_buf.append(''.join(word_buf)) word_buf = [] elif cur_char in TAILING_CHARS: word_buf.append(cur_char) sent_buf.append(''.join(word_buf)) word_buf = [] elif cur_char == '.': word = ''.join(word_buf) if ( i + OFFSET_OF_NEXT_WORD < max_index and re.match(r'[A-Z]', text[i + OFFSET_OF_NEXT_WORD]) and not in_bracket and re.match(r'[a-z\)\]\}]', text[i - 1]) ): sent_buf.append(word + cur_char) sent_list.append(helper.optimize_space(' '.join(sent_buf))) sent_buf = [] word_buf = [] elif re.match(r'[A-Z]', word): word_buf.append(cur_char) else: sent_buf.append(word + cur_char) word_buf = [] elif cur_char in BRACKET_MAP_OPEN: word_buf.append(cur_char) bracket_stack.append(cur_char) in_bracket = True elif cur_char in BRACKET_MAP_CLOSE: try: open_bracket = bracket_stack.pop() if BRACKET_MAP_CLOSE[cur_char] == open_bracket: word_buf.append(cur_char) else: word_buf.append(BRACKET_MAP_OPEN[open_bracket]) except IndexError: word_buf.append('') in_bracket = False else: word_buf.append(cur_char) return sent_list def word_tokenize(text, clean=False): ''' Tokenize sentence to words. In this version, we split by special characters. If optional parameter 'clean' is set, special characters will cleaned. ''' tokens = _clean_space(re.split(r'([\W\.]+)', text)) if clean: tokens = _clean_special_chars(tokens) return tokens def _clean_space(tokens): return filter(lambda token: token != ' ', tokens) def _clean_special_chars(tokens): return filter(lambda token: re.match(r'(\w+)', token), tokens)
lib/nlp/tokenizer.py
import re from lib.nlp import helper OFFSET_OF_NEXT_WORD = 2 BRACKET_MAP_OPEN = {'[': ']', '(': ')', '{': '}'} BRACKET_MAP_CLOSE = {']': '[', ')': '(', '}': '{'} TAILING_CHARS = [':', ';', '?', '!', ','] def sent_tokenize(text): ''' Sentence segmentation with user specific algorithm. NOTE: It's might be better for bioinformatics publication only. ''' text = helper.remove_newline(text) text = helper.optimize_space(text) sent_list = [] sent_buf = [] word_buf = [] bracket_stack = [] in_bracket = False text_len = len(text) max_index = text_len - 1 for i in range(text_len): cur_char = text[i] if i == max_index: sent_buf.append(''.join(word_buf) + cur_char) sent_list.append(helper.optimize_space(' '.join(sent_buf))) word_buf = [] sent_buf = [] break if cur_char == ' ': sent_buf.append(''.join(word_buf)) word_buf = [] elif cur_char in TAILING_CHARS: word_buf.append(cur_char) sent_buf.append(''.join(word_buf)) word_buf = [] elif cur_char == '.': word = ''.join(word_buf) if ( i + OFFSET_OF_NEXT_WORD < max_index and re.match(r'[A-Z]', text[i + OFFSET_OF_NEXT_WORD]) and not in_bracket and re.match(r'[a-z\)\]\}]', text[i - 1]) ): sent_buf.append(word + cur_char) sent_list.append(helper.optimize_space(' '.join(sent_buf))) sent_buf = [] word_buf = [] elif re.match(r'[A-Z]', word): word_buf.append(cur_char) else: sent_buf.append(word + cur_char) word_buf = [] elif cur_char in BRACKET_MAP_OPEN: word_buf.append(cur_char) bracket_stack.append(cur_char) in_bracket = True elif cur_char in BRACKET_MAP_CLOSE: try: open_bracket = bracket_stack.pop() if BRACKET_MAP_CLOSE[cur_char] == open_bracket: word_buf.append(cur_char) else: word_buf.append(BRACKET_MAP_OPEN[open_bracket]) except IndexError: word_buf.append('') in_bracket = False else: word_buf.append(cur_char) return sent_list def word_tokenize(text, clean=False): ''' Tokenize sentence to words. In this version, we split by special characters. If optional parameter 'clean' is set, special characters will cleaned. ''' tokens = _clean_space(re.split(r'([\W\.]+)', text)) if clean: tokens = _clean_special_chars(tokens) return tokens def _clean_space(tokens): return filter(lambda token: token != ' ', tokens) def _clean_special_chars(tokens): return filter(lambda token: re.match(r'(\w+)', token), tokens)
0.253491
0.155335
import pandas as pd import numpy as np from sklearn.decomposition import PCA,TruncatedSVD,NMF from sklearn.preprocessing import Normalizer import argparse import time import numba @numba.jit(nopython=True) def year_binner(year,val=10): return year - year%val parser = argparse.ArgumentParser(description='Perform dimentionality reduction of the count-based vectors, using SVD') parser.add_argument('--contextual', action='store_true', help='Is the model contextual') parser.add_argument('--temporal', action='store_true', help='Is the model temporal') parser.add_argument('--seed', type=int, default=1991, help='random seed') parser.add_argument('--dims', type=int, default=300, help='Desired number of reduced dimensions') parser.add_argument('--save_format', type=str,default='pkl', help='In what format should the reduced datasets be saved : csv or pkl') args = parser.parse_args() modifier_list=pkl.load( open("modifier_list_reduced.pkl",'rb')) head_list=pkl.load( open("head_list_reduced.pkl",'rb')) t1=time.time() # Dimentionality Reduction using SVD def dim_reduction(df,rows): df_svd = TruncatedSVD(n_components=args.dims, n_iter=10, random_state=args.seed) print(f'Explained variance ratio {(df_svd.fit(df).explained_variance_ratio_.sum()):2.3f}') #df_list=df_svd.fit(df).explained_variance_ratio_ df_reduced = df_svd.fit_transform(df) df_reduced = Normalizer(copy=False).fit_transform(df_reduced) df_reduced=pd.DataFrame(df_reduced,index=rows) #df_reduced.reset_index(inplace=True) if args.temporal: df_reduced.index = pd.MultiIndex.from_tuples(df_reduced.index, names=['common', 'decade']) return df_reduced def common_reduction(df): df.reset_index(inplace=True) df.year=df.year.astype("int32") df=df.query('1800 <= year <= 2010').copy() df['time']=year_binner(df['year'].values,10) df=df.groupby(['modifier','head','context','time'])['count'].sum().to_frame() df.reset_index(inplace=True) df=df.loc[df.groupby(['modifier','head','time'])['count'].transform('sum').gt(50)] df=df.loc[df['modifier'].isin(modifier_list) & df['head'].isin(head_list)] return df if args.contextual: print("CompoundCentric Model") comp_str='CompoundCentric' print("Loading the constituent and compound vector datasets") heads=pd.read_csv("/data/dharp/compounding/datasets/heads_reduced.csv",sep="\t") #heads=heads.query('decade != 2000') heads.columns=['common','decade','context','count'] heads['common']=heads['common'].str.replace(r'_n$', r'_h', regex=True) modifiers=pd.read_csv("/data/dharp/compounding/datasets/modifiers_reduced.csv",sep="\t") #modifiers=modifiers.query('decade != 2000') modifiers.columns=['common','decade','context','count'] modifiers['common']=modifiers['common'].str.replace(r'_n$', r'_m', regex=True) compounds=pd.read_pickle("/data/dharp/compounding/datasets/compounds.pkl") compounds=common_reduction(compounds) compounds['common']=compounds['modifier']+" "+compounds['head'] if args.temporal: print("DecadeCentric Model") compounds=compounds.groupby(['common','decade','context'])['count'].sum() modifiers=modifiers.groupby(['common','decade','context'])['count'].sum() heads=heads.groupby(['common','decade','context'])['count'].sum() else: print("DecadeAgnostic Model") compounds=compounds.groupby(['common','context'])['count'].sum() modifiers=modifiers.groupby(['common','context'])['count'].sum() heads=heads.groupby(['common','context'])['count'].sum() print('Concatenating all the datasets together') df=pd.concat([heads,modifiers,compounds]) else: print("CompoundAgnostic Model") comp_str='CompoundAgnostic' print("Loading the word and phrase vector datasets") constituents=pd.read_csv("/data/dharp/compounding/datasets/words.csv") constituents.columns=['common','context','decade','count'] #constituents=constituents.query('decade != 2000') compounds=pd.read_csv("/data/dharp/compounding/datasets/phrases.csv") compounds.columns=['modifier','head','context','decade','count'] #compounds=compounds.query('decade != 2000') compounds['common']=compounds['modifier']+" "+compounds['head'] if args.temporal: print("DecadeCentric Model") compounds=compounds.groupby(['common','decade','context'])['count'].sum() constituents=constituents.groupby(['common','decade','context'])['count'].sum() else: print("DecadeAgnostic Model") compounds=compounds.groupby(['common','context'])['count'].sum() constituents=constituents.groupby(['common','context'])['count'].sum() print('Concatenating all the datasets together') df=pd.concat([constituents,compounds]) df=df.to_sparse() if args.temporal: df, rows, _ = df.to_coo(row_levels=['common','decade'],column_levels=['context'],sort_labels=False) dec_str='DecadeCentric' else: df, rows, _ = df.to_coo(row_levels=['common'],column_levels=['context'],sort_labels=False) dec_str='DecadeAgnostic' print('Running SVD') df_reduced=dim_reduction(df,rows) #df_reduced.reset_index(inplace=True) print('Splitting back into individual datasets are saving them') if args.temporal: df_reduced.index.names = ['common','decade'] else: df_reduced.index.names = ['common'] compounds_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.contains(r'\w \w')] compounds_reduced.reset_index(inplace=True) #print(compounds_reduced.head()) compounds_reduced['modifier'],compounds_reduced['head']=compounds_reduced['common'].str.split(' ', 1).str dim_str=str(args.dims) if args.contextual: heads_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.endswith(r'_h')] heads_reduced.reset_index(inplace=True) heads_reduced['head']=heads_reduced['common'].str.replace(r'_h$', r'_n', regex=True) heads_reduced.drop(['common'],axis=1,inplace=True) modifiers_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.endswith(r'_m')] modifiers_reduced.reset_index(inplace=True) modifiers_reduced['modifier']=modifiers_reduced['common'].str.replace(r'_m$', r'_n', regex=True) modifiers_reduced.drop(['common'],axis=1,inplace=True) if args.temporal: compounds_reduced.set_index(['modifier','head','decade'],inplace=True) heads_reduced.set_index(['head','decade'],inplace=True) modifiers_reduced.set_index(['modifier','decade'],inplace=True) else: compounds_reduced.set_index(['modifier','head'],inplace=True) heads_reduced.set_index(['head'],inplace=True) modifiers_reduced.set_index(['modifier'],inplace=True) print('Saving the files') if args.save_format=='pkl': compounds_reduced.to_pickle('/data/dharp/compounding/datasets/compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') heads_reduced.to_pickle('/data/dharp/compounding/datasets/heads_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') modifiers_reduced.to_pickle('/data/dharp/compounding/datasets/modifiers_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') elif args.save_format=='csv': compounds_reduced.to_csv("/data/dharp/compounding/datasets/"+'compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') heads_reduced.to_csv('/data/dharp/compounding/datasets/heads_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') modifiers_reduced.to_pickle('/data/dharp/compounding/datasets/modifiers_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') else: constituents_reduced=df_reduced.loc[~df_reduced.index.get_level_values(0).str.contains(r'\w \w')] if args.temporal: compounds_reduced.set_index(['modifier','head','decade'],inplace=True) else: compounds_reduced.set_index(['modifier','head'],inplace=True) print('Saving the files') if args.save_format=='pkl': compounds_reduced.to_pickle('/data/dharp/compounding/datasets/compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') constituents_reduced.to_pickle('/data/dharp/compounding/datasets/constituents_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') elif args.save_format=='csv': compounds_reduced.to_csv("/data/dharp/compounding/datasets/"+'compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') constituents_reduced.to_csv('/data/dharp/compounding/datasets/constituents_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') print(f'Time taken {time.time()-t1:10.3f}')
src/dimensionality_reduction.py
import pandas as pd import numpy as np from sklearn.decomposition import PCA,TruncatedSVD,NMF from sklearn.preprocessing import Normalizer import argparse import time import numba @numba.jit(nopython=True) def year_binner(year,val=10): return year - year%val parser = argparse.ArgumentParser(description='Perform dimentionality reduction of the count-based vectors, using SVD') parser.add_argument('--contextual', action='store_true', help='Is the model contextual') parser.add_argument('--temporal', action='store_true', help='Is the model temporal') parser.add_argument('--seed', type=int, default=1991, help='random seed') parser.add_argument('--dims', type=int, default=300, help='Desired number of reduced dimensions') parser.add_argument('--save_format', type=str,default='pkl', help='In what format should the reduced datasets be saved : csv or pkl') args = parser.parse_args() modifier_list=pkl.load( open("modifier_list_reduced.pkl",'rb')) head_list=pkl.load( open("head_list_reduced.pkl",'rb')) t1=time.time() # Dimentionality Reduction using SVD def dim_reduction(df,rows): df_svd = TruncatedSVD(n_components=args.dims, n_iter=10, random_state=args.seed) print(f'Explained variance ratio {(df_svd.fit(df).explained_variance_ratio_.sum()):2.3f}') #df_list=df_svd.fit(df).explained_variance_ratio_ df_reduced = df_svd.fit_transform(df) df_reduced = Normalizer(copy=False).fit_transform(df_reduced) df_reduced=pd.DataFrame(df_reduced,index=rows) #df_reduced.reset_index(inplace=True) if args.temporal: df_reduced.index = pd.MultiIndex.from_tuples(df_reduced.index, names=['common', 'decade']) return df_reduced def common_reduction(df): df.reset_index(inplace=True) df.year=df.year.astype("int32") df=df.query('1800 <= year <= 2010').copy() df['time']=year_binner(df['year'].values,10) df=df.groupby(['modifier','head','context','time'])['count'].sum().to_frame() df.reset_index(inplace=True) df=df.loc[df.groupby(['modifier','head','time'])['count'].transform('sum').gt(50)] df=df.loc[df['modifier'].isin(modifier_list) & df['head'].isin(head_list)] return df if args.contextual: print("CompoundCentric Model") comp_str='CompoundCentric' print("Loading the constituent and compound vector datasets") heads=pd.read_csv("/data/dharp/compounding/datasets/heads_reduced.csv",sep="\t") #heads=heads.query('decade != 2000') heads.columns=['common','decade','context','count'] heads['common']=heads['common'].str.replace(r'_n$', r'_h', regex=True) modifiers=pd.read_csv("/data/dharp/compounding/datasets/modifiers_reduced.csv",sep="\t") #modifiers=modifiers.query('decade != 2000') modifiers.columns=['common','decade','context','count'] modifiers['common']=modifiers['common'].str.replace(r'_n$', r'_m', regex=True) compounds=pd.read_pickle("/data/dharp/compounding/datasets/compounds.pkl") compounds=common_reduction(compounds) compounds['common']=compounds['modifier']+" "+compounds['head'] if args.temporal: print("DecadeCentric Model") compounds=compounds.groupby(['common','decade','context'])['count'].sum() modifiers=modifiers.groupby(['common','decade','context'])['count'].sum() heads=heads.groupby(['common','decade','context'])['count'].sum() else: print("DecadeAgnostic Model") compounds=compounds.groupby(['common','context'])['count'].sum() modifiers=modifiers.groupby(['common','context'])['count'].sum() heads=heads.groupby(['common','context'])['count'].sum() print('Concatenating all the datasets together') df=pd.concat([heads,modifiers,compounds]) else: print("CompoundAgnostic Model") comp_str='CompoundAgnostic' print("Loading the word and phrase vector datasets") constituents=pd.read_csv("/data/dharp/compounding/datasets/words.csv") constituents.columns=['common','context','decade','count'] #constituents=constituents.query('decade != 2000') compounds=pd.read_csv("/data/dharp/compounding/datasets/phrases.csv") compounds.columns=['modifier','head','context','decade','count'] #compounds=compounds.query('decade != 2000') compounds['common']=compounds['modifier']+" "+compounds['head'] if args.temporal: print("DecadeCentric Model") compounds=compounds.groupby(['common','decade','context'])['count'].sum() constituents=constituents.groupby(['common','decade','context'])['count'].sum() else: print("DecadeAgnostic Model") compounds=compounds.groupby(['common','context'])['count'].sum() constituents=constituents.groupby(['common','context'])['count'].sum() print('Concatenating all the datasets together') df=pd.concat([constituents,compounds]) df=df.to_sparse() if args.temporal: df, rows, _ = df.to_coo(row_levels=['common','decade'],column_levels=['context'],sort_labels=False) dec_str='DecadeCentric' else: df, rows, _ = df.to_coo(row_levels=['common'],column_levels=['context'],sort_labels=False) dec_str='DecadeAgnostic' print('Running SVD') df_reduced=dim_reduction(df,rows) #df_reduced.reset_index(inplace=True) print('Splitting back into individual datasets are saving them') if args.temporal: df_reduced.index.names = ['common','decade'] else: df_reduced.index.names = ['common'] compounds_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.contains(r'\w \w')] compounds_reduced.reset_index(inplace=True) #print(compounds_reduced.head()) compounds_reduced['modifier'],compounds_reduced['head']=compounds_reduced['common'].str.split(' ', 1).str dim_str=str(args.dims) if args.contextual: heads_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.endswith(r'_h')] heads_reduced.reset_index(inplace=True) heads_reduced['head']=heads_reduced['common'].str.replace(r'_h$', r'_n', regex=True) heads_reduced.drop(['common'],axis=1,inplace=True) modifiers_reduced=df_reduced.loc[df_reduced.index.get_level_values(0).str.endswith(r'_m')] modifiers_reduced.reset_index(inplace=True) modifiers_reduced['modifier']=modifiers_reduced['common'].str.replace(r'_m$', r'_n', regex=True) modifiers_reduced.drop(['common'],axis=1,inplace=True) if args.temporal: compounds_reduced.set_index(['modifier','head','decade'],inplace=True) heads_reduced.set_index(['head','decade'],inplace=True) modifiers_reduced.set_index(['modifier','decade'],inplace=True) else: compounds_reduced.set_index(['modifier','head'],inplace=True) heads_reduced.set_index(['head'],inplace=True) modifiers_reduced.set_index(['modifier'],inplace=True) print('Saving the files') if args.save_format=='pkl': compounds_reduced.to_pickle('/data/dharp/compounding/datasets/compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') heads_reduced.to_pickle('/data/dharp/compounding/datasets/heads_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') modifiers_reduced.to_pickle('/data/dharp/compounding/datasets/modifiers_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') elif args.save_format=='csv': compounds_reduced.to_csv("/data/dharp/compounding/datasets/"+'compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') heads_reduced.to_csv('/data/dharp/compounding/datasets/heads_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') modifiers_reduced.to_pickle('/data/dharp/compounding/datasets/modifiers_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') else: constituents_reduced=df_reduced.loc[~df_reduced.index.get_level_values(0).str.contains(r'\w \w')] if args.temporal: compounds_reduced.set_index(['modifier','head','decade'],inplace=True) else: compounds_reduced.set_index(['modifier','head'],inplace=True) print('Saving the files') if args.save_format=='pkl': compounds_reduced.to_pickle('/data/dharp/compounding/datasets/compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') constituents_reduced.to_pickle('/data/dharp/compounding/datasets/constituents_'+comp_str+'_'+dec_str+'_'+dim_str+'.pkl') elif args.save_format=='csv': compounds_reduced.to_csv("/data/dharp/compounding/datasets/"+'compounds_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') constituents_reduced.to_csv('/data/dharp/compounding/datasets/constituents_'+comp_str+'_'+dec_str+'_'+dim_str+'.csv',header=False,sep='\t') print(f'Time taken {time.time()-t1:10.3f}')
0.479747
0.208209
from __future__ import division import numpy as np import random import pygame from shapely.geometry import LineString # pyGame initialization FPS = 60 QFPS = 240 SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 pygame.init() FPS_CLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("King Pong") pygame.font.init() SCORE_FONT = pygame.font.Font(None, 64) GAMES_FONT = pygame.font.Font(None, 16) # Paddle dimensions PADDLE_WIDTH, PADDLE_HEIGHT = 8, 64 PADDLE_UPPER_SECTION = 3*PADDLE_HEIGHT/8 PADDLE_BOTTOM_SECTION = 5*PADDLE_HEIGHT/8 TOP_SPEED = 5 PADDLE_SPEED = TOP_SPEED PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE = 16, int(SCREEN_HEIGHT/2) # Ball BALL_SIZE = 8 class GameState: """ Game State Representation Game state with function to act based on user actions. """ def __init__(self, auto_draw = True): self.auto_draw = auto_draw self.print_scores = False self.top_speed = TOP_SPEED self.reset_positions() self.first_to = [1000, 5] self.games = [0, 0] self.score = [0, 0] self.score_changed = False def score_last_changed(self): """ Checks if the scores has changed since the last time this function was accessed """ current = self.score_changed self.score_changed = False return current def game_over(self): """ The game is over when any player reaches the number of games playing to """ return self.games[0] == self.first_to[0] or \ self.games[1] == self.first_to[0] def reset_positions(self): """ Moves the players to a center position and reset the direction and speed of the ball randomly within acceptable range. """ self.playerx, self.playery = SCREEN_WIDTH-PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE self.cpux, self.cpuy = PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE self.ballx, self.bally = SCREEN_WIDTH/2, SCREEN_HEIGHT/2 self.ball_speed_x = random.choice( range(-self.top_speed+1, -int(2*self.top_speed/3)) + range(int(2*self.top_speed/3), self.top_speed)) self.ball_speed_y = random.choice( range(-self.top_speed+1, -int(2*self.top_speed/3)) + range(int(2*self.top_speed/3), self.top_speed)) def frame_step(self, input_actions): """ Moves the state of the game forward one step with the given input actions input_actions[0] == 1: do nothing input_actions[1] == 1: move up input_actions[2] == 1: move down sum(input_actions) == 1 """ pygame.event.pump() if sum(input_actions) != 1: raise ValueError('Multiple input actions!') # move player if input_actions[1] == 1: # player moves up self.playery = np.maximum(0, self.playery - self.top_speed) elif input_actions[2] == 1: # player moves down self.playery = np.minimum(self.playery + self.top_speed, SCREEN_HEIGHT - PADDLE_HEIGHT) # move cpu if self.cpuy + (PADDLE_HEIGHT/2) > self.bally: self.cpuy = np.maximum(0, self.cpuy - self.top_speed) elif self.cpuy + (PADDLE_HEIGHT/2) < self.bally: self.cpuy = np.minimum(self.cpuy + self.top_speed, SCREEN_HEIGHT - PADDLE_HEIGHT) # move ball get reward the it produced reward = self.move_ball() # check for losing terminal_good = self.ballx <= 0 terminal_bad = self.ballx + BALL_SIZE >= SCREEN_WIDTH terminal = terminal_good or terminal_bad if terminal: self.reset_positions() self.score[0] += terminal_bad self.score[1] += terminal_good reward = -1.0 if terminal_bad else 1.0 if terminal_good else reward # redraw game onto screen SCREEN.fill((0, 0, 0)) # black screen pygame.draw.rect(SCREEN, # left 'cpu' player (255, 255, 255), (self.cpux, self.cpuy, PADDLE_WIDTH, PADDLE_HEIGHT)) pygame.draw.rect(SCREEN, # right player (255, 255, 255), (self.playerx, self.playery, PADDLE_WIDTH, PADDLE_HEIGHT)) pygame.draw.rect(SCREEN, # ball (255, 255, 255), (self.ballx, self.bally, BALL_SIZE, BALL_SIZE)) # update pygame image_data = pygame.surfarray.array3d(pygame.display.get_surface()) if self.auto_draw: self.complete_drawing() if terminal: self.score_changed = True # calculate who would be the winner if self.score[0] == self.first_to[1]: self.score = [0, 0] self.games[0] += 1 elif self.score[1] == self.first_to[1]: self.score = [0, 0] self.games[1] += 1 return image_data, reward def move_ball(self): """ Move the ball in game state it calculates boundaries and it clips the ball positioning when it is overlapping with walls or paddles return rewards when right player makes contact with the ball and when ball leaves the game screen on the left side """ reward = 0.0 # get ball trajectory prev_x, prev_y = self.ballx, self.bally next_x, next_y = self.ballx + self.ball_speed_x, self.bally + self.ball_speed_y ball_trajectory = LineString([(prev_x, prev_y), (next_x, next_y)]) # get possible collision lines upper_wall = LineString([(0, 0), (SCREEN_WIDTH, 0)]) bottom_wall = LineString([(0, SCREEN_HEIGHT - BALL_SIZE), (SCREEN_WIDTH, SCREEN_HEIGHT - BALL_SIZE)]) left_paddle = LineString([(self.cpux + PADDLE_WIDTH, self.cpuy - BALL_SIZE), (self.cpux + PADDLE_WIDTH, self.cpuy + PADDLE_HEIGHT)]) right_paddle = LineString([(self.playerx - BALL_SIZE, self.playery - BALL_SIZE), (self.playerx - BALL_SIZE, self.playery + PADDLE_HEIGHT)]) # chop ball trajectory when colliding if ball_trajectory.intersects(upper_wall): self.ball_speed_y *= -1 upper = ball_trajectory.intersection(upper_wall) self.ballx, self.bally = upper.x, upper.y + 1 elif ball_trajectory.intersects(bottom_wall): self.ball_speed_y *= -1 bottom = ball_trajectory.intersection(bottom_wall) self.ballx, self.bally = bottom.x, bottom.y - 1 elif ball_trajectory.intersects(left_paddle): left = ball_trajectory.intersection(left_paddle) contact_point = left.y - left_paddle.xy[1][0] if contact_point < PADDLE_UPPER_SECTION or \ contact_point > PADDLE_BOTTOM_SECTION: self.flip_and_spin_ball() else: self.flip_and_speed_ball() self.ballx, self.bally = left.x + 1, left.y elif ball_trajectory.intersects(right_paddle): reward += 0.1 right = ball_trajectory.intersection(right_paddle) contact_point = right.y - right_paddle.xy[1][0] if contact_point < PADDLE_UPPER_SECTION or \ contact_point > PADDLE_BOTTOM_SECTION: self.flip_and_spin_ball() else: self.flip_and_speed_ball() self.ballx, self.bally = right.x - 1, right.y else: self.ballx += self.ball_speed_x self.bally += self.ball_speed_y return reward def draw_scores(self): """ To be called when playing against human only so that numbers pixels don't interfere with learning """ cpu_score = SCORE_FONT.render(str(self.score[0]), 1, (255, 255, 255)) cpu_games = GAMES_FONT.render(str(self.games[0]), 1, (255, 255, 255)) my_score = SCORE_FONT.render(str(self.score[1]), 1, (255, 255, 255)) my_games = GAMES_FONT.render(str(self.games[1]), 1, (255, 255, 255)) SCREEN.blit(cpu_score, (32, 16)) SCREEN.blit(cpu_games, (32 - 4, 16)) SCREEN.blit(my_score, (SCREEN_HEIGHT+92, 16)) SCREEN.blit(my_games, (SCREEN_HEIGHT+92 - 4, 16)) def complete_drawing(self): """ Force the drawing of the screens """ if self.print_scores: self.draw_scores() pygame.display.flip() if self.auto_draw: FPS_CLOCK.tick(QFPS) else: FPS_CLOCK.tick(FPS) def flip_and_spin_ball(self): """ When ball makes contact with the upper or lower ends of either paddle, the ball will potentially randomly increase the y axis speed and be return with the same speed """ self.ball_speed_x *= -1 self.ball_speed_y *= random.randint(1000, 1200)/1000. def flip_and_speed_ball(self): """ When the ball makes contact with the center of either paddle, it will return the ball with potentially an increase in the x axis speed y axis remains untouched """ self.ball_speed_x *= -1 self.ball_speed_x *= random.randint(1000, 1200)/1000. def main(argv): """ When called `python king_pong.py` a CPU is allocated to play against a human """ game_state = GameState(auto_draw = False) # 2 game_states of 1 point game_state.first_to = [3, 2] game_state.top_speed = 5 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() keys = pygame.key.get_pressed() a1 = keys[pygame.K_UP] a2 = 0 if a1 else keys[pygame.K_DOWN] a0 = 1 if not a1 and not a2 else 0 image_data, reward = game_state.frame_step([a0, a1, a2]) game_state.draw_scores() game_state.complete_drawing() if game_state.game_over(): exit(0) if __name__ == "__main__": from sys import argv main(argv)
king_pong.py
from __future__ import division import numpy as np import random import pygame from shapely.geometry import LineString # pyGame initialization FPS = 60 QFPS = 240 SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 pygame.init() FPS_CLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("King Pong") pygame.font.init() SCORE_FONT = pygame.font.Font(None, 64) GAMES_FONT = pygame.font.Font(None, 16) # Paddle dimensions PADDLE_WIDTH, PADDLE_HEIGHT = 8, 64 PADDLE_UPPER_SECTION = 3*PADDLE_HEIGHT/8 PADDLE_BOTTOM_SECTION = 5*PADDLE_HEIGHT/8 TOP_SPEED = 5 PADDLE_SPEED = TOP_SPEED PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE = 16, int(SCREEN_HEIGHT/2) # Ball BALL_SIZE = 8 class GameState: """ Game State Representation Game state with function to act based on user actions. """ def __init__(self, auto_draw = True): self.auto_draw = auto_draw self.print_scores = False self.top_speed = TOP_SPEED self.reset_positions() self.first_to = [1000, 5] self.games = [0, 0] self.score = [0, 0] self.score_changed = False def score_last_changed(self): """ Checks if the scores has changed since the last time this function was accessed """ current = self.score_changed self.score_changed = False return current def game_over(self): """ The game is over when any player reaches the number of games playing to """ return self.games[0] == self.first_to[0] or \ self.games[1] == self.first_to[0] def reset_positions(self): """ Moves the players to a center position and reset the direction and speed of the ball randomly within acceptable range. """ self.playerx, self.playery = SCREEN_WIDTH-PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE self.cpux, self.cpuy = PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE self.ballx, self.bally = SCREEN_WIDTH/2, SCREEN_HEIGHT/2 self.ball_speed_x = random.choice( range(-self.top_speed+1, -int(2*self.top_speed/3)) + range(int(2*self.top_speed/3), self.top_speed)) self.ball_speed_y = random.choice( range(-self.top_speed+1, -int(2*self.top_speed/3)) + range(int(2*self.top_speed/3), self.top_speed)) def frame_step(self, input_actions): """ Moves the state of the game forward one step with the given input actions input_actions[0] == 1: do nothing input_actions[1] == 1: move up input_actions[2] == 1: move down sum(input_actions) == 1 """ pygame.event.pump() if sum(input_actions) != 1: raise ValueError('Multiple input actions!') # move player if input_actions[1] == 1: # player moves up self.playery = np.maximum(0, self.playery - self.top_speed) elif input_actions[2] == 1: # player moves down self.playery = np.minimum(self.playery + self.top_speed, SCREEN_HEIGHT - PADDLE_HEIGHT) # move cpu if self.cpuy + (PADDLE_HEIGHT/2) > self.bally: self.cpuy = np.maximum(0, self.cpuy - self.top_speed) elif self.cpuy + (PADDLE_HEIGHT/2) < self.bally: self.cpuy = np.minimum(self.cpuy + self.top_speed, SCREEN_HEIGHT - PADDLE_HEIGHT) # move ball get reward the it produced reward = self.move_ball() # check for losing terminal_good = self.ballx <= 0 terminal_bad = self.ballx + BALL_SIZE >= SCREEN_WIDTH terminal = terminal_good or terminal_bad if terminal: self.reset_positions() self.score[0] += terminal_bad self.score[1] += terminal_good reward = -1.0 if terminal_bad else 1.0 if terminal_good else reward # redraw game onto screen SCREEN.fill((0, 0, 0)) # black screen pygame.draw.rect(SCREEN, # left 'cpu' player (255, 255, 255), (self.cpux, self.cpuy, PADDLE_WIDTH, PADDLE_HEIGHT)) pygame.draw.rect(SCREEN, # right player (255, 255, 255), (self.playerx, self.playery, PADDLE_WIDTH, PADDLE_HEIGHT)) pygame.draw.rect(SCREEN, # ball (255, 255, 255), (self.ballx, self.bally, BALL_SIZE, BALL_SIZE)) # update pygame image_data = pygame.surfarray.array3d(pygame.display.get_surface()) if self.auto_draw: self.complete_drawing() if terminal: self.score_changed = True # calculate who would be the winner if self.score[0] == self.first_to[1]: self.score = [0, 0] self.games[0] += 1 elif self.score[1] == self.first_to[1]: self.score = [0, 0] self.games[1] += 1 return image_data, reward def move_ball(self): """ Move the ball in game state it calculates boundaries and it clips the ball positioning when it is overlapping with walls or paddles return rewards when right player makes contact with the ball and when ball leaves the game screen on the left side """ reward = 0.0 # get ball trajectory prev_x, prev_y = self.ballx, self.bally next_x, next_y = self.ballx + self.ball_speed_x, self.bally + self.ball_speed_y ball_trajectory = LineString([(prev_x, prev_y), (next_x, next_y)]) # get possible collision lines upper_wall = LineString([(0, 0), (SCREEN_WIDTH, 0)]) bottom_wall = LineString([(0, SCREEN_HEIGHT - BALL_SIZE), (SCREEN_WIDTH, SCREEN_HEIGHT - BALL_SIZE)]) left_paddle = LineString([(self.cpux + PADDLE_WIDTH, self.cpuy - BALL_SIZE), (self.cpux + PADDLE_WIDTH, self.cpuy + PADDLE_HEIGHT)]) right_paddle = LineString([(self.playerx - BALL_SIZE, self.playery - BALL_SIZE), (self.playerx - BALL_SIZE, self.playery + PADDLE_HEIGHT)]) # chop ball trajectory when colliding if ball_trajectory.intersects(upper_wall): self.ball_speed_y *= -1 upper = ball_trajectory.intersection(upper_wall) self.ballx, self.bally = upper.x, upper.y + 1 elif ball_trajectory.intersects(bottom_wall): self.ball_speed_y *= -1 bottom = ball_trajectory.intersection(bottom_wall) self.ballx, self.bally = bottom.x, bottom.y - 1 elif ball_trajectory.intersects(left_paddle): left = ball_trajectory.intersection(left_paddle) contact_point = left.y - left_paddle.xy[1][0] if contact_point < PADDLE_UPPER_SECTION or \ contact_point > PADDLE_BOTTOM_SECTION: self.flip_and_spin_ball() else: self.flip_and_speed_ball() self.ballx, self.bally = left.x + 1, left.y elif ball_trajectory.intersects(right_paddle): reward += 0.1 right = ball_trajectory.intersection(right_paddle) contact_point = right.y - right_paddle.xy[1][0] if contact_point < PADDLE_UPPER_SECTION or \ contact_point > PADDLE_BOTTOM_SECTION: self.flip_and_spin_ball() else: self.flip_and_speed_ball() self.ballx, self.bally = right.x - 1, right.y else: self.ballx += self.ball_speed_x self.bally += self.ball_speed_y return reward def draw_scores(self): """ To be called when playing against human only so that numbers pixels don't interfere with learning """ cpu_score = SCORE_FONT.render(str(self.score[0]), 1, (255, 255, 255)) cpu_games = GAMES_FONT.render(str(self.games[0]), 1, (255, 255, 255)) my_score = SCORE_FONT.render(str(self.score[1]), 1, (255, 255, 255)) my_games = GAMES_FONT.render(str(self.games[1]), 1, (255, 255, 255)) SCREEN.blit(cpu_score, (32, 16)) SCREEN.blit(cpu_games, (32 - 4, 16)) SCREEN.blit(my_score, (SCREEN_HEIGHT+92, 16)) SCREEN.blit(my_games, (SCREEN_HEIGHT+92 - 4, 16)) def complete_drawing(self): """ Force the drawing of the screens """ if self.print_scores: self.draw_scores() pygame.display.flip() if self.auto_draw: FPS_CLOCK.tick(QFPS) else: FPS_CLOCK.tick(FPS) def flip_and_spin_ball(self): """ When ball makes contact with the upper or lower ends of either paddle, the ball will potentially randomly increase the y axis speed and be return with the same speed """ self.ball_speed_x *= -1 self.ball_speed_y *= random.randint(1000, 1200)/1000. def flip_and_speed_ball(self): """ When the ball makes contact with the center of either paddle, it will return the ball with potentially an increase in the x axis speed y axis remains untouched """ self.ball_speed_x *= -1 self.ball_speed_x *= random.randint(1000, 1200)/1000. def main(argv): """ When called `python king_pong.py` a CPU is allocated to play against a human """ game_state = GameState(auto_draw = False) # 2 game_states of 1 point game_state.first_to = [3, 2] game_state.top_speed = 5 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() keys = pygame.key.get_pressed() a1 = keys[pygame.K_UP] a2 = 0 if a1 else keys[pygame.K_DOWN] a0 = 1 if not a1 and not a2 else 0 image_data, reward = game_state.frame_step([a0, a1, a2]) game_state.draw_scores() game_state.complete_drawing() if game_state.game_over(): exit(0) if __name__ == "__main__": from sys import argv main(argv)
0.744378
0.178526
import django.core.validators import django.db.models.deletion import django.utils.timezone import django_fsm import model_utils.fields from django.db import migrations, models import waldur_core.core.fields import waldur_core.core.models import waldur_core.logging.loggers class Migration(migrations.Migration): initial = True dependencies = [ ('structure', '0001_squashed_0054'), ] operations = [ migrations.CreateModel( name='Invoice', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('uuid', waldur_core.core.fields.UUIDField()), ( 'state', models.CharField( choices=[ ('DRAFT', 'Draft'), ('SENT', 'Sent'), ('PAID', 'Paid'), ('MARKED_AS_PAID', 'Marked as paid'), ('CANCELLED', 'Cancelled'), ('REFUNDED', 'Refunded'), ('PARTIALLY_REFUNDED', 'Partially refunded'), ('MARKED_AS_REFUNDED', 'Marked as refunded'), ('UNPAID', 'Unpaid'), ('PAYMENT_PENDING', 'Payment pending'), ], default='DRAFT', max_length=30, ), ), ('invoice_date', models.DateField()), ('end_date', models.DateField()), ( 'pdf', models.FileField( blank=True, null=True, upload_to='paypal-invoices' ), ), ('number', models.CharField(max_length=30)), ( 'tax_percent', models.DecimalField( decimal_places=2, default=0, max_digits=4, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], ), ), ('backend_id', models.CharField(blank=True, max_length=128)), ( 'issuer_details', waldur_core.core.fields.JSONField( blank=True, default={}, help_text='Stores data about invoice issuer', ), ), ( 'payment_details', waldur_core.core.fields.JSONField( blank=True, default={}, help_text='Stores data about customer payment details', ), ), ( 'month', models.PositiveSmallIntegerField( validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(12), ] ), ), ('year', models.PositiveSmallIntegerField()), ( 'customer', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='paypal_invoices', to='structure.Customer', ), ), ], options={'ordering': ['-invoice_date'],}, bases=( waldur_core.logging.loggers.LoggableMixin, models.Model, waldur_core.core.models.BackendModelMixin, ), ), migrations.CreateModel( name='InvoiceItem', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('price', models.DecimalField(decimal_places=2, max_digits=9)), ('tax', models.DecimalField(decimal_places=2, default=0, max_digits=9)), ('unit_price', models.DecimalField(decimal_places=2, max_digits=9)), ('quantity', models.PositiveIntegerField(default=0)), ( 'unit_of_measure', models.CharField( choices=[ ('QUANTITY', 'Quantity'), ('HOURS', 'Hours'), ('AMOUNT', 'Amount'), ], default='HOURS', max_length=30, ), ), ('name', models.CharField(max_length=255)), ('start', models.DateTimeField(null=True)), ('end', models.DateTimeField(null=True)), ( 'invoice', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='items', to='waldur_paypal.Invoice', ), ), ], options={'ordering': ['invoice', '-start'],}, ), migrations.CreateModel( name='Payment', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ( 'created', model_utils.fields.AutoCreatedField( default=django.utils.timezone.now, editable=False, verbose_name='created', ), ), ( 'modified', model_utils.fields.AutoLastModifiedField( default=django.utils.timezone.now, editable=False, verbose_name='modified', ), ), ('uuid', waldur_core.core.fields.UUIDField()), ('error_message', models.TextField(blank=True)), ( 'state', django_fsm.FSMIntegerField( choices=[ (0, 'Initial'), (1, 'Created'), (2, 'Approved'), (4, 'Erred'), ], default=0, ), ), ('amount', models.DecimalField(decimal_places=2, max_digits=9)), ('tax', models.DecimalField(decimal_places=2, default=0, max_digits=9)), ('backend_id', models.CharField(max_length=255, null=True)), ('token', models.CharField(max_length=255, null=True)), ('approval_url', models.URLField()), ( 'customer', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='structure.Customer', ), ), ], options={'ordering': ['-modified'],}, bases=(waldur_core.logging.loggers.LoggableMixin, models.Model), ), ]
src/waldur_paypal/migrations/0001_initial.py
import django.core.validators import django.db.models.deletion import django.utils.timezone import django_fsm import model_utils.fields from django.db import migrations, models import waldur_core.core.fields import waldur_core.core.models import waldur_core.logging.loggers class Migration(migrations.Migration): initial = True dependencies = [ ('structure', '0001_squashed_0054'), ] operations = [ migrations.CreateModel( name='Invoice', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('uuid', waldur_core.core.fields.UUIDField()), ( 'state', models.CharField( choices=[ ('DRAFT', 'Draft'), ('SENT', 'Sent'), ('PAID', 'Paid'), ('MARKED_AS_PAID', 'Marked as paid'), ('CANCELLED', 'Cancelled'), ('REFUNDED', 'Refunded'), ('PARTIALLY_REFUNDED', 'Partially refunded'), ('MARKED_AS_REFUNDED', 'Marked as refunded'), ('UNPAID', 'Unpaid'), ('PAYMENT_PENDING', 'Payment pending'), ], default='DRAFT', max_length=30, ), ), ('invoice_date', models.DateField()), ('end_date', models.DateField()), ( 'pdf', models.FileField( blank=True, null=True, upload_to='paypal-invoices' ), ), ('number', models.CharField(max_length=30)), ( 'tax_percent', models.DecimalField( decimal_places=2, default=0, max_digits=4, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], ), ), ('backend_id', models.CharField(blank=True, max_length=128)), ( 'issuer_details', waldur_core.core.fields.JSONField( blank=True, default={}, help_text='Stores data about invoice issuer', ), ), ( 'payment_details', waldur_core.core.fields.JSONField( blank=True, default={}, help_text='Stores data about customer payment details', ), ), ( 'month', models.PositiveSmallIntegerField( validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(12), ] ), ), ('year', models.PositiveSmallIntegerField()), ( 'customer', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='paypal_invoices', to='structure.Customer', ), ), ], options={'ordering': ['-invoice_date'],}, bases=( waldur_core.logging.loggers.LoggableMixin, models.Model, waldur_core.core.models.BackendModelMixin, ), ), migrations.CreateModel( name='InvoiceItem', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('price', models.DecimalField(decimal_places=2, max_digits=9)), ('tax', models.DecimalField(decimal_places=2, default=0, max_digits=9)), ('unit_price', models.DecimalField(decimal_places=2, max_digits=9)), ('quantity', models.PositiveIntegerField(default=0)), ( 'unit_of_measure', models.CharField( choices=[ ('QUANTITY', 'Quantity'), ('HOURS', 'Hours'), ('AMOUNT', 'Amount'), ], default='HOURS', max_length=30, ), ), ('name', models.CharField(max_length=255)), ('start', models.DateTimeField(null=True)), ('end', models.DateTimeField(null=True)), ( 'invoice', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='items', to='waldur_paypal.Invoice', ), ), ], options={'ordering': ['invoice', '-start'],}, ), migrations.CreateModel( name='Payment', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ( 'created', model_utils.fields.AutoCreatedField( default=django.utils.timezone.now, editable=False, verbose_name='created', ), ), ( 'modified', model_utils.fields.AutoLastModifiedField( default=django.utils.timezone.now, editable=False, verbose_name='modified', ), ), ('uuid', waldur_core.core.fields.UUIDField()), ('error_message', models.TextField(blank=True)), ( 'state', django_fsm.FSMIntegerField( choices=[ (0, 'Initial'), (1, 'Created'), (2, 'Approved'), (4, 'Erred'), ], default=0, ), ), ('amount', models.DecimalField(decimal_places=2, max_digits=9)), ('tax', models.DecimalField(decimal_places=2, default=0, max_digits=9)), ('backend_id', models.CharField(max_length=255, null=True)), ('token', models.CharField(max_length=255, null=True)), ('approval_url', models.URLField()), ( 'customer', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='structure.Customer', ), ), ], options={'ordering': ['-modified'],}, bases=(waldur_core.logging.loggers.LoggableMixin, models.Model), ), ]
0.442396
0.146789
import abc import torch import torch.nn as nn import torch.nn.functional as F from .cfg import Config from .SphereProjection import SphereProjection class RowBilinear(nn.Module): def __init__(self, n_in, kernel_shapes, pad=0): super(RowBilinear, self).__init__() n_transform = kernel_shapes.size(0) weights = [] self.pad = pad for i in range(n_transform): kH = kernel_shapes[i,0].item() kW = kernel_shapes[i,1].item() n_out = (kH + 2 * pad) * (kW + 2 * pad) weight = nn.Parameter(torch.Tensor(n_out, n_in)) weights.append(weight) self.weights = nn.ParameterList(weights) def forward(self, x, row): weight = self.weights[row] return F.linear(x, weight) class KTN(nn.Module): __metaclass__ = abc.ABCMeta def __init__(self, kernel, bias, kernel_shapes, **kwargs): super(KTN, self).__init__() dtype = Config["FloatType"] self.src_kernel = nn.Parameter(kernel)#.type(dtype) self.src_bias = nn.Parameter(bias)#.type(dtype) self.activation = torch.tanh self.register_buffer("kernel_shapes", kernel_shapes) n_out, n_in, kH, kW = kernel.size() self.n_in = n_in self.n_out = n_out self.n_maps = n_out * n_in kernel_size = kH * kW self.initialize_ktn(kernel_size) @abc.abstractmethod def initialize_ktn(self, kernel_size): pass def forward(self, row): x = self.src_kernel.view(self.n_maps, -1) x = self.apply_ktn(x, row) okH, okW = self.kernel_shapes[row] kernel = x.view(self.n_out, self.n_in, okH, okW) bias = self.src_bias return kernel, bias @abc.abstractmethod def apply_ktn(self, x, row): pass def initialize_weight(self): for name, param in self.named_parameters(): if ".bias" in name: param.data.zero_() elif ".weight" in name: param.data.normal_(std=0.01) def update_group(self, group): for name, param in self.named_parameters(): param.requires_grad = False if group == "kernel": self.src_kernel.requires_grad = True self.src_bias.requires_grad = True elif group == "transform": for name, param in self.named_parameters(): if ".weight" in name or ".bias" in name: param.requires_grad = True elif group == "all": for name, param in self.named_parameters(): param.requires_grad = True else: raise ValueError("Unknown parameter group") class BilinearKTN(KTN): def initialize_ktn(self, kernel_size): self.bilinear = RowBilinear(kernel_size, self.kernel_shapes) def apply_ktn(self, x, row): x = self.bilinear(x, row) return x def initialize_weight(self, **kwargs): for name, param in self.named_parameters(): if name[-5:] == ".bias": param.data.zero_() elif name[-7:] == ".weight": param.data.normal_(std=0.01) self.initialize_bilinear(self.bilinear, **kwargs) def initialize_bilinear(self, bilinear, sphereH=320, fov=65.5, imgW=640, dilation=1, tied_weights=5): kH = self.src_kernel.size(2) sphereW = sphereH * 2 projection = SphereProjection(kernel_size=kH, sphereH=sphereH, sphereW=sphereW, view_angle=fov, imgW=imgW) center = sphereW / 2 for i, param in enumerate(bilinear.weights): param.data.zero_() tilt = i * tied_weights + tied_weights / 2 P = projection.buildP(tilt=tilt).transpose() okH = self.kernel_shapes[i,0].item() okW = self.kernel_shapes[i,1].item() okH += bilinear.pad * 2 okW += bilinear.pad * 2 sH = int(tilt - okH / 2) sW = int(center - okW / 2) for y in range(okH): row = y + sH if row < 0 or row >= sphereH: continue for x in range(okW): col = x + sW if col < 0 or col >= sphereW: continue pixel = row * sphereW + col p = P[pixel] if p.nnz == 0: continue j = y * okW + x for k in range(p.shape[1]): param.data[j,k] = p[0,k] class ResidualKTN(BilinearKTN): def initialize_ktn(self, kernel_size): self.bilinear = RowBilinear(kernel_size, self.kernel_shapes) self.res1 = RowBilinear(kernel_size, self.kernel_shapes, pad=2) self.res2 = nn.Conv2d(self.n_in, self.n_in, 1) self.res3 = nn.Conv2d(1, 1, 3, padding=0) self.res4 = nn.Conv2d(self.n_in, self.n_in, 1) self.res5 = nn.Conv2d(1, 1, 3, padding=0) def apply_ktn(self, x, row): base = self.bilinear(x, row) okH, okW = self.kernel_shapes[row] x = self.res1(x, row) x = x.view(-1, self.n_in, okH+4, okW+4) x = self.res2(self.activation(x)) x = x.view(-1, 1, okH+4, okW+4) x = self.res3(self.activation(x)) x = x.view(-1, self.n_in, okH+2, okW+2) x = self.res4(self.activation(x)) x = x.view(-1, 1, okH+2, okW+2) x = self.res5(self.activation(x)) x = x.view(base.size()) x = x + base return x def initialize_weight(self, **kwargs): for name, param in self.named_parameters(): if name[-5:] == ".bias": param.data.zero_() elif name[-7:] == ".weight": param.data.normal_(std=0.01) self.initialize_bilinear(self.bilinear, **kwargs) self.initialize_bilinear(self.res1, **kwargs) KTN_ARCHS = { "bilinear": BilinearKTN, "residual": ResidualKTN, }
model/KernelTransformer/KTN.py
import abc import torch import torch.nn as nn import torch.nn.functional as F from .cfg import Config from .SphereProjection import SphereProjection class RowBilinear(nn.Module): def __init__(self, n_in, kernel_shapes, pad=0): super(RowBilinear, self).__init__() n_transform = kernel_shapes.size(0) weights = [] self.pad = pad for i in range(n_transform): kH = kernel_shapes[i,0].item() kW = kernel_shapes[i,1].item() n_out = (kH + 2 * pad) * (kW + 2 * pad) weight = nn.Parameter(torch.Tensor(n_out, n_in)) weights.append(weight) self.weights = nn.ParameterList(weights) def forward(self, x, row): weight = self.weights[row] return F.linear(x, weight) class KTN(nn.Module): __metaclass__ = abc.ABCMeta def __init__(self, kernel, bias, kernel_shapes, **kwargs): super(KTN, self).__init__() dtype = Config["FloatType"] self.src_kernel = nn.Parameter(kernel)#.type(dtype) self.src_bias = nn.Parameter(bias)#.type(dtype) self.activation = torch.tanh self.register_buffer("kernel_shapes", kernel_shapes) n_out, n_in, kH, kW = kernel.size() self.n_in = n_in self.n_out = n_out self.n_maps = n_out * n_in kernel_size = kH * kW self.initialize_ktn(kernel_size) @abc.abstractmethod def initialize_ktn(self, kernel_size): pass def forward(self, row): x = self.src_kernel.view(self.n_maps, -1) x = self.apply_ktn(x, row) okH, okW = self.kernel_shapes[row] kernel = x.view(self.n_out, self.n_in, okH, okW) bias = self.src_bias return kernel, bias @abc.abstractmethod def apply_ktn(self, x, row): pass def initialize_weight(self): for name, param in self.named_parameters(): if ".bias" in name: param.data.zero_() elif ".weight" in name: param.data.normal_(std=0.01) def update_group(self, group): for name, param in self.named_parameters(): param.requires_grad = False if group == "kernel": self.src_kernel.requires_grad = True self.src_bias.requires_grad = True elif group == "transform": for name, param in self.named_parameters(): if ".weight" in name or ".bias" in name: param.requires_grad = True elif group == "all": for name, param in self.named_parameters(): param.requires_grad = True else: raise ValueError("Unknown parameter group") class BilinearKTN(KTN): def initialize_ktn(self, kernel_size): self.bilinear = RowBilinear(kernel_size, self.kernel_shapes) def apply_ktn(self, x, row): x = self.bilinear(x, row) return x def initialize_weight(self, **kwargs): for name, param in self.named_parameters(): if name[-5:] == ".bias": param.data.zero_() elif name[-7:] == ".weight": param.data.normal_(std=0.01) self.initialize_bilinear(self.bilinear, **kwargs) def initialize_bilinear(self, bilinear, sphereH=320, fov=65.5, imgW=640, dilation=1, tied_weights=5): kH = self.src_kernel.size(2) sphereW = sphereH * 2 projection = SphereProjection(kernel_size=kH, sphereH=sphereH, sphereW=sphereW, view_angle=fov, imgW=imgW) center = sphereW / 2 for i, param in enumerate(bilinear.weights): param.data.zero_() tilt = i * tied_weights + tied_weights / 2 P = projection.buildP(tilt=tilt).transpose() okH = self.kernel_shapes[i,0].item() okW = self.kernel_shapes[i,1].item() okH += bilinear.pad * 2 okW += bilinear.pad * 2 sH = int(tilt - okH / 2) sW = int(center - okW / 2) for y in range(okH): row = y + sH if row < 0 or row >= sphereH: continue for x in range(okW): col = x + sW if col < 0 or col >= sphereW: continue pixel = row * sphereW + col p = P[pixel] if p.nnz == 0: continue j = y * okW + x for k in range(p.shape[1]): param.data[j,k] = p[0,k] class ResidualKTN(BilinearKTN): def initialize_ktn(self, kernel_size): self.bilinear = RowBilinear(kernel_size, self.kernel_shapes) self.res1 = RowBilinear(kernel_size, self.kernel_shapes, pad=2) self.res2 = nn.Conv2d(self.n_in, self.n_in, 1) self.res3 = nn.Conv2d(1, 1, 3, padding=0) self.res4 = nn.Conv2d(self.n_in, self.n_in, 1) self.res5 = nn.Conv2d(1, 1, 3, padding=0) def apply_ktn(self, x, row): base = self.bilinear(x, row) okH, okW = self.kernel_shapes[row] x = self.res1(x, row) x = x.view(-1, self.n_in, okH+4, okW+4) x = self.res2(self.activation(x)) x = x.view(-1, 1, okH+4, okW+4) x = self.res3(self.activation(x)) x = x.view(-1, self.n_in, okH+2, okW+2) x = self.res4(self.activation(x)) x = x.view(-1, 1, okH+2, okW+2) x = self.res5(self.activation(x)) x = x.view(base.size()) x = x + base return x def initialize_weight(self, **kwargs): for name, param in self.named_parameters(): if name[-5:] == ".bias": param.data.zero_() elif name[-7:] == ".weight": param.data.normal_(std=0.01) self.initialize_bilinear(self.bilinear, **kwargs) self.initialize_bilinear(self.res1, **kwargs) KTN_ARCHS = { "bilinear": BilinearKTN, "residual": ResidualKTN, }
0.905259
0.304752
import typing from pylark.lark_request import Response from pylark.api_service_drive_file_search import ( SearchDriveFileReq, SearchDriveFileResp, _gen_search_drive_file_req, ) from pylark.api_service_drive_file_meta_get import ( GetDriveFileMetaReq, GetDriveFileMetaResp, _gen_get_drive_file_meta_req, ) from pylark.api_service_drive_file_create import ( CreateDriveFileReq, CreateDriveFileResp, _gen_create_drive_file_req, ) from pylark.api_service_drive_file_copy import ( CopyDriveFileReq, CopyDriveFileResp, _gen_copy_drive_file_req, ) from pylark.api_service_drive_file_delete import ( DeleteDriveFileReq, DeleteDriveFileResp, _gen_delete_drive_file_req, ) from pylark.api_service_drive_file_sheet_delete import ( DeleteDriveSheetFileReq, DeleteDriveSheetFileResp, _gen_delete_drive_sheet_file_req, ) from pylark.api_service_drive_folder_create import ( CreateDriveFolderReq, CreateDriveFolderResp, _gen_create_drive_folder_req, ) from pylark.api_service_drive_folder_meta import ( GetDriveFolderMetaReq, GetDriveFolderMetaResp, _gen_get_drive_folder_meta_req, ) from pylark.api_service_drive_folder_root_meta import ( GetDriveRootFolderMetaReq, GetDriveRootFolderMetaResp, _gen_get_drive_root_folder_meta_req, ) from pylark.api_service_drive_folder_children_get import ( GetDriveFolderChildrenReq, GetDriveFolderChildrenResp, _gen_get_drive_folder_children_req, ) from pylark.api_service_drive_file_statistics_get import ( GetDriveFileStatisticsReq, GetDriveFileStatisticsResp, _gen_get_drive_file_statistics_req, ) from pylark.api_service_drive_file_download import ( DownloadDriveFileReq, DownloadDriveFileResp, _gen_download_drive_file_req, ) from pylark.api_service_drive_file_upload_all import ( UploadDriveFileReq, UploadDriveFileResp, _gen_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_prepare import ( PrepareUploadDriveFileReq, PrepareUploadDriveFileResp, _gen_prepare_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_part import ( PartUploadDriveFileReq, PartUploadDriveFileResp, _gen_part_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_finish import ( FinishUploadDriveFileReq, FinishUploadDriveFileResp, _gen_finish_upload_drive_file_req, ) from pylark.api_service_drive_media_download import ( DownloadDriveMediaReq, DownloadDriveMediaResp, _gen_download_drive_media_req, ) from pylark.api_service_drive_media_upload_all import ( UploadDriveMediaReq, UploadDriveMediaResp, _gen_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_prepare import ( PrepareUploadDriveMediaReq, PrepareUploadDriveMediaResp, _gen_prepare_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_part import ( PartUploadDriveMediaReq, PartUploadDriveMediaResp, _gen_part_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_finish import ( FinishUploadDriveMediaReq, FinishUploadDriveMediaResp, _gen_finish_upload_drive_media_req, ) from pylark.api_service_drive_permission_member_create_old import ( CreateDriveMemberPermissionOldReq, CreateDriveMemberPermissionOldResp, _gen_create_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_transfer import ( TransferDriveMemberPermissionReq, TransferDriveMemberPermissionResp, _gen_transfer_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_list import ( GetDriveMemberPermissionListReq, GetDriveMemberPermissionListResp, _gen_get_drive_member_permission_list_req, ) from pylark.api_service_drive_permission_member_create import ( CreateDriveMemberPermissionReq, CreateDriveMemberPermissionResp, _gen_create_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_delete_old import ( DeleteDriveMemberPermissionOldReq, DeleteDriveMemberPermissionOldResp, _gen_delete_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_delete import ( DeleteDriveMemberPermissionReq, DeleteDriveMemberPermissionResp, _gen_delete_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_update_old import ( UpdateDriveMemberPermissionOldReq, UpdateDriveMemberPermissionOldResp, _gen_update_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_update import ( UpdateDriveMemberPermissionReq, UpdateDriveMemberPermissionResp, _gen_update_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_check import ( CheckDriveMemberPermissionReq, CheckDriveMemberPermissionResp, _gen_check_drive_member_permission_req, ) from pylark.api_service_drive_permission_public_update_v1_old import ( UpdateDrivePublicPermissionV1OldReq, UpdateDrivePublicPermissionV1OldResp, _gen_update_drive_public_permission_v1_old_req, ) from pylark.api_service_drive_permission_public_update_v2_old import ( UpdateDrivePublicPermissionV2OldReq, UpdateDrivePublicPermissionV2OldResp, _gen_update_drive_public_permission_v2_old_req, ) from pylark.api_service_drive_permission_public_get_v2 import ( GetDrivePublicPermissionV2Req, GetDrivePublicPermissionV2Resp, _gen_get_drive_public_permission_v2_req, ) from pylark.api_service_drive_permission_public_patch import ( UpdateDrivePublicPermissionReq, UpdateDrivePublicPermissionResp, _gen_update_drive_public_permission_req, ) from pylark.api_service_drive_media_batch_get_tmp_download_url import ( BatchGetDriveMediaTmpDownloadURLReq, BatchGetDriveMediaTmpDownloadURLResp, _gen_batch_get_drive_media_tmp_download_url_req, ) from pylark.api_service_drive_comment_list import ( GetDriveCommentListReq, GetDriveCommentListResp, _gen_get_drive_comment_list_req, ) from pylark.api_service_drive_comment_get import ( GetDriveCommentReq, GetDriveCommentResp, _gen_get_drive_comment_req, ) from pylark.api_service_drive_comment_create import ( CreateDriveCommentReq, CreateDriveCommentResp, _gen_create_drive_comment_req, ) from pylark.api_service_drive_comment_update import ( UpdateDriveCommentReq, UpdateDriveCommentResp, _gen_update_drive_comment_req, ) from pylark.api_service_drive_comment_delete import ( DeleteDriveCommentReq, DeleteDriveCommentResp, _gen_delete_drive_comment_req, ) from pylark.api_service_drive_comment_patch import ( UpdateDriveCommentPatchReq, UpdateDriveCommentPatchResp, _gen_update_drive_comment_patch_req, ) from pylark.api_service_drive_doc_create import ( CreateDriveDocReq, CreateDriveDocResp, _gen_create_drive_doc_req, ) from pylark.api_service_drive_doc_content_get import ( GetDriveDocContentReq, GetDriveDocContentResp, _gen_get_drive_doc_content_req, ) from pylark.api_service_drive_doc_raw_content_get import ( GetDriveDocRawContentReq, GetDriveDocRawContentResp, _gen_get_drive_doc_raw_content_req, ) from pylark.api_service_drive_doc_meta_get import ( GetDriveDocMetaReq, GetDriveDocMetaResp, _gen_get_drive_doc_meta_req, ) from pylark.api_service_drive_sheet_create import ( CreateSheetReq, CreateSheetResp, _gen_create_sheet_req, ) from pylark.api_service_drive_sheet_meta_get import ( GetSheetMetaReq, GetSheetMetaResp, _gen_get_sheet_meta_req, ) from pylark.api_service_drive_sheet_property_update import ( UpdateSheetPropertyReq, UpdateSheetPropertyResp, _gen_update_sheet_property_req, ) from pylark.api_service_drive_sheet_batch_update import ( BatchUpdateSheetReq, BatchUpdateSheetResp, _gen_batch_update_sheet_req, ) from pylark.api_service_drive_sheet_import import ( ImportSheetReq, ImportSheetResp, _gen_import_sheet_req, ) from pylark.api_service_drive_import_task_create import ( CreateDriveImportTaskReq, CreateDriveImportTaskResp, _gen_create_drive_import_task_req, ) from pylark.api_service_drive_import_task_get import ( GetDriveImportTaskReq, GetDriveImportTaskResp, _gen_get_drive_import_task_req, ) from pylark.api_service_drive_sheet_dimension_move import ( MoveSheetDimensionReq, MoveSheetDimensionResp, _gen_move_sheet_dimension_req, ) from pylark.api_service_drive_sheet_value_prepend import ( PrependSheetValueReq, PrependSheetValueResp, _gen_prepend_sheet_value_req, ) from pylark.api_service_drive_sheet_value_append import ( AppendSheetValueReq, AppendSheetValueResp, _gen_append_sheet_value_req, ) from pylark.api_service_drive_sheet_dimension_range_insert import ( InsertSheetDimensionRangeReq, InsertSheetDimensionRangeResp, _gen_insert_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_add import ( AddSheetDimensionRangeReq, AddSheetDimensionRangeResp, _gen_add_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_update import ( UpdateSheetDimensionRangeReq, UpdateSheetDimensionRangeResp, _gen_update_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_delete import ( DeleteSheetDimensionRangeReq, DeleteSheetDimensionRangeResp, _gen_delete_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_value_get import ( GetSheetValueReq, GetSheetValueResp, _gen_get_sheet_value_req, ) from pylark.api_service_drive_sheet_value_batch_get import ( BatchGetSheetValueReq, BatchGetSheetValueResp, _gen_batch_get_sheet_value_req, ) from pylark.api_service_drive_sheet_value_set import ( SetSheetValueReq, SetSheetValueResp, _gen_set_sheet_value_req, ) from pylark.api_service_drive_sheet_value_batch_set import ( BatchSetSheetValueReq, BatchSetSheetValueResp, _gen_batch_set_sheet_value_req, ) from pylark.api_service_drive_sheet_style_set import ( SetSheetStyleReq, SetSheetStyleResp, _gen_set_sheet_style_req, ) from pylark.api_service_drive_sheet_style_batch_set import ( BatchSetSheetStyleReq, BatchSetSheetStyleResp, _gen_batch_set_sheet_style_req, ) from pylark.api_service_drive_sheet_cell_merge import ( MergeSheetCellReq, MergeSheetCellResp, _gen_merge_sheet_cell_req, ) from pylark.api_service_drive_sheet_cell_unmerge import ( UnmergeSheetCellReq, UnmergeSheetCellResp, _gen_unmerge_sheet_cell_req, ) from pylark.api_service_drive_sheet_image_set import ( SetSheetValueImageReq, SetSheetValueImageResp, _gen_set_sheet_value_image_req, ) from pylark.api_service_drive_sheet_find import ( FindSheetReq, FindSheetResp, _gen_find_sheet_req, ) from pylark.api_service_drive_sheet_replace import ( ReplaceSheetReq, ReplaceSheetResp, _gen_replace_sheet_req, ) from pylark.api_service_drive_sheet_condition_format_create import ( CreateSheetConditionFormatReq, CreateSheetConditionFormatResp, _gen_create_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_get import ( GetSheetConditionFormatReq, GetSheetConditionFormatResp, _gen_get_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_update import ( UpdateSheetConditionFormatReq, UpdateSheetConditionFormatResp, _gen_update_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_delete import ( DeleteSheetConditionFormatReq, DeleteSheetConditionFormatResp, _gen_delete_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_protected_dimension_create import ( CreateSheetProtectedDimensionReq, CreateSheetProtectedDimensionResp, _gen_create_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_get import ( GetSheetProtectedDimensionReq, GetSheetProtectedDimensionResp, _gen_get_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_update import ( UpdateSheetProtectedDimensionReq, UpdateSheetProtectedDimensionResp, _gen_update_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_delete import ( DeleteSheetProtectedDimensionReq, DeleteSheetProtectedDimensionResp, _gen_delete_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_create import ( CreateSheetDataValidationDropdownReq, CreateSheetDataValidationDropdownResp, _gen_create_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_delete import ( DeleteSheetDataValidationDropdownReq, DeleteSheetDataValidationDropdownResp, _gen_delete_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_update import ( UpdateSheetDataValidationDropdownReq, UpdateSheetDataValidationDropdownResp, _gen_update_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_get import ( GetSheetDataValidationDropdownReq, GetSheetDataValidationDropdownResp, _gen_get_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_filter_create import ( CreateSheetFilterReq, CreateSheetFilterResp, _gen_create_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_delete import ( DeleteSheetFilterReq, DeleteSheetFilterResp, _gen_delete_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_update import ( UpdateSheetFilterReq, UpdateSheetFilterResp, _gen_update_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_get import ( GetSheetFilterReq, GetSheetFilterResp, _gen_get_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_view_create import ( CreateSheetFilterViewReq, CreateSheetFilterViewResp, _gen_create_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_delete import ( DeleteSheetFilterViewReq, DeleteSheetFilterViewResp, _gen_delete_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_update import ( UpdateSheetFilterViewReq, UpdateSheetFilterViewResp, _gen_update_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_get import ( GetSheetFilterViewReq, GetSheetFilterViewResp, _gen_get_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_query import ( QuerySheetFilterViewReq, QuerySheetFilterViewResp, _gen_query_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_condition_create import ( CreateSheetFilterViewConditionReq, CreateSheetFilterViewConditionResp, _gen_create_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_delete import ( DeleteSheetFilterViewConditionReq, DeleteSheetFilterViewConditionResp, _gen_delete_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_update import ( UpdateSheetFilterViewConditionReq, UpdateSheetFilterViewConditionResp, _gen_update_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_get import ( GetSheetFilterViewConditionReq, GetSheetFilterViewConditionResp, _gen_get_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_query import ( QuerySheetFilterViewConditionReq, QuerySheetFilterViewConditionResp, _gen_query_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_float_image_create import ( CreateSheetFloatImageReq, CreateSheetFloatImageResp, _gen_create_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_delete import ( DeleteSheetFloatImageReq, DeleteSheetFloatImageResp, _gen_delete_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_update import ( UpdateSheetFloatImageReq, UpdateSheetFloatImageResp, _gen_update_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_get import ( GetSheetFloatImageReq, GetSheetFloatImageResp, _gen_get_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_query import ( QuerySheetFloatImageReq, QuerySheetFloatImageResp, _gen_query_sheet_float_image_req, ) from pylark.api_service_drive_wiki_space_create import ( CreateWikiSpaceReq, CreateWikiSpaceResp, _gen_create_wiki_space_req, ) from pylark.api_service_drive_wiki_space_get_list import ( GetWikiSpaceListReq, GetWikiSpaceListResp, _gen_get_wiki_space_list_req, ) from pylark.api_service_drive_wiki_space_get import ( GetWikiSpaceReq, GetWikiSpaceResp, _gen_get_wiki_space_req, ) from pylark.api_service_drive_wiki_space_setting_update import ( UpdateWikiSpaceSettingReq, UpdateWikiSpaceSettingResp, _gen_update_wiki_space_setting_req, ) from pylark.api_service_drive_wiki_space_member_add import ( AddWikiSpaceMemberReq, AddWikiSpaceMemberResp, _gen_add_wiki_space_member_req, ) from pylark.api_service_drive_wiki_node_create import ( CreateWikiNodeReq, CreateWikiNodeResp, _gen_create_wiki_node_req, ) from pylark.api_service_drive_wiki_node_list import ( GetWikiNodeListReq, GetWikiNodeListResp, _gen_get_wiki_node_list_req, ) from pylark.api_service_drive_wiki_node_get import ( GetWikiNodeReq, GetWikiNodeResp, _gen_get_wiki_node_req, ) from pylark.api_service_drive_wiki_move_docs_to_wiki import ( MoveDocsToWikiReq, MoveDocsToWikiResp, _gen_move_docs_to_wiki_req, ) if typing.TYPE_CHECKING: from lark import Lark class LarkDriveService(object): cli: "Lark" def __init__(self, cli: "Lark"): self.cli = cli def search_drive_file( self, request: SearchDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[SearchDriveFileResp, Response]: return self.cli.raw_request(_gen_search_drive_file_req(request, options)) def get_drive_file_meta( self, request: GetDriveFileMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFileMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_file_meta_req(request, options)) def create_drive_file( self, request: CreateDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveFileResp, Response]: return self.cli.raw_request(_gen_create_drive_file_req(request, options)) def copy_drive_file( self, request: CopyDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[CopyDriveFileResp, Response]: return self.cli.raw_request(_gen_copy_drive_file_req(request, options)) def delete_drive_file( self, request: DeleteDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveFileResp, Response]: return self.cli.raw_request(_gen_delete_drive_file_req(request, options)) def delete_drive_sheet_file( self, request: DeleteDriveSheetFileReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveSheetFileResp, Response]: return self.cli.raw_request(_gen_delete_drive_sheet_file_req(request, options)) def create_drive_folder( self, request: CreateDriveFolderReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveFolderResp, Response]: return self.cli.raw_request(_gen_create_drive_folder_req(request, options)) def get_drive_folder_meta( self, request: GetDriveFolderMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFolderMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_folder_meta_req(request, options)) def get_drive_root_folder_meta( self, request: GetDriveRootFolderMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveRootFolderMetaResp, Response]: return self.cli.raw_request( _gen_get_drive_root_folder_meta_req(request, options) ) def get_drive_folder_children( self, request: GetDriveFolderChildrenReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFolderChildrenResp, Response]: return self.cli.raw_request( _gen_get_drive_folder_children_req(request, options) ) def get_drive_file_statistics( self, request: GetDriveFileStatisticsReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFileStatisticsResp, Response]: return self.cli.raw_request( _gen_get_drive_file_statistics_req(request, options) ) def download_drive_file( self, request: DownloadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[DownloadDriveFileResp, Response]: return self.cli.raw_request(_gen_download_drive_file_req(request, options)) def upload_drive_file( self, request: UploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[UploadDriveFileResp, Response]: return self.cli.raw_request(_gen_upload_drive_file_req(request, options)) def prepare_upload_drive_file( self, request: PrepareUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[PrepareUploadDriveFileResp, Response]: return self.cli.raw_request( _gen_prepare_upload_drive_file_req(request, options) ) def part_upload_drive_file( self, request: PartUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[PartUploadDriveFileResp, Response]: return self.cli.raw_request(_gen_part_upload_drive_file_req(request, options)) def finish_upload_drive_file( self, request: FinishUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[FinishUploadDriveFileResp, Response]: return self.cli.raw_request(_gen_finish_upload_drive_file_req(request, options)) def download_drive_media( self, request: DownloadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[DownloadDriveMediaResp, Response]: return self.cli.raw_request(_gen_download_drive_media_req(request, options)) def upload_drive_media( self, request: UploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[UploadDriveMediaResp, Response]: return self.cli.raw_request(_gen_upload_drive_media_req(request, options)) def prepare_upload_drive_media( self, request: PrepareUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[PrepareUploadDriveMediaResp, Response]: return self.cli.raw_request( _gen_prepare_upload_drive_media_req(request, options) ) def part_upload_drive_media( self, request: PartUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[PartUploadDriveMediaResp, Response]: return self.cli.raw_request(_gen_part_upload_drive_media_req(request, options)) def finish_upload_drive_media( self, request: FinishUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[FinishUploadDriveMediaResp, Response]: return self.cli.raw_request( _gen_finish_upload_drive_media_req(request, options) ) def create_drive_member_permission_old( self, request: CreateDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_create_drive_member_permission_old_req(request, options) ) def transfer_drive_member_permission( self, request: TransferDriveMemberPermissionReq, options: typing.List[str] = None, ) -> typing.Tuple[TransferDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_transfer_drive_member_permission_req(request, options) ) def get_drive_member_permission_list( self, request: GetDriveMemberPermissionListReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveMemberPermissionListResp, Response]: return self.cli.raw_request( _gen_get_drive_member_permission_list_req(request, options) ) def create_drive_member_permission( self, request: CreateDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_create_drive_member_permission_req(request, options) ) def delete_drive_member_permission_old( self, request: DeleteDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_delete_drive_member_permission_old_req(request, options) ) def delete_drive_member_permission( self, request: DeleteDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_delete_drive_member_permission_req(request, options) ) def update_drive_member_permission_old( self, request: UpdateDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_update_drive_member_permission_old_req(request, options) ) def update_drive_member_permission( self, request: UpdateDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_update_drive_member_permission_req(request, options) ) def check_drive_member_permission( self, request: CheckDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[CheckDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_check_drive_member_permission_req(request, options) ) def update_drive_public_permission_v1_old( self, request: UpdateDrivePublicPermissionV1OldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDrivePublicPermissionV1OldResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_v1_old_req(request, options) ) def update_drive_public_permission_v2_old( self, request: UpdateDrivePublicPermissionV2OldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDrivePublicPermissionV2OldResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_v2_old_req(request, options) ) def get_drive_public_permission_v2( self, request: GetDrivePublicPermissionV2Req, options: typing.List[str] = None ) -> typing.Tuple[GetDrivePublicPermissionV2Resp, Response]: return self.cli.raw_request( _gen_get_drive_public_permission_v2_req(request, options) ) def update_drive_public_permission( self, request: UpdateDrivePublicPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDrivePublicPermissionResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_req(request, options) ) def batch_get_drive_media_tmp_download_url( self, request: BatchGetDriveMediaTmpDownloadURLReq, options: typing.List[str] = None, ) -> typing.Tuple[BatchGetDriveMediaTmpDownloadURLResp, Response]: return self.cli.raw_request( _gen_batch_get_drive_media_tmp_download_url_req(request, options) ) def get_drive_comment_list( self, request: GetDriveCommentListReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveCommentListResp, Response]: return self.cli.raw_request(_gen_get_drive_comment_list_req(request, options)) def get_drive_comment( self, request: GetDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveCommentResp, Response]: return self.cli.raw_request(_gen_get_drive_comment_req(request, options)) def create_drive_comment( self, request: CreateDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveCommentResp, Response]: return self.cli.raw_request(_gen_create_drive_comment_req(request, options)) def update_drive_comment( self, request: UpdateDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveCommentResp, Response]: return self.cli.raw_request(_gen_update_drive_comment_req(request, options)) def delete_drive_comment( self, request: DeleteDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveCommentResp, Response]: return self.cli.raw_request(_gen_delete_drive_comment_req(request, options)) def update_drive_comment_patch( self, request: UpdateDriveCommentPatchReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveCommentPatchResp, Response]: return self.cli.raw_request( _gen_update_drive_comment_patch_req(request, options) ) def create_drive_doc( self, request: CreateDriveDocReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveDocResp, Response]: return self.cli.raw_request(_gen_create_drive_doc_req(request, options)) def get_drive_doc_content( self, request: GetDriveDocContentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocContentResp, Response]: return self.cli.raw_request(_gen_get_drive_doc_content_req(request, options)) def get_drive_doc_raw_content( self, request: GetDriveDocRawContentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocRawContentResp, Response]: return self.cli.raw_request( _gen_get_drive_doc_raw_content_req(request, options) ) def get_drive_doc_meta( self, request: GetDriveDocMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_doc_meta_req(request, options)) def create_sheet( self, request: CreateSheetReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetResp, Response]: return self.cli.raw_request(_gen_create_sheet_req(request, options)) def get_sheet_meta( self, request: GetSheetMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetMetaResp, Response]: return self.cli.raw_request(_gen_get_sheet_meta_req(request, options)) def update_sheet_property( self, request: UpdateSheetPropertyReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetPropertyResp, Response]: return self.cli.raw_request(_gen_update_sheet_property_req(request, options)) def batch_update_sheet( self, request: BatchUpdateSheetReq, options: typing.List[str] = None ) -> typing.Tuple[BatchUpdateSheetResp, Response]: return self.cli.raw_request(_gen_batch_update_sheet_req(request, options)) def import_sheet( self, request: ImportSheetReq, options: typing.List[str] = None ) -> typing.Tuple[ImportSheetResp, Response]: return self.cli.raw_request(_gen_import_sheet_req(request, options)) def create_drive_import_task( self, request: CreateDriveImportTaskReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveImportTaskResp, Response]: return self.cli.raw_request(_gen_create_drive_import_task_req(request, options)) def get_drive_import_task( self, request: GetDriveImportTaskReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveImportTaskResp, Response]: return self.cli.raw_request(_gen_get_drive_import_task_req(request, options)) def move_sheet_dimension( self, request: MoveSheetDimensionReq, options: typing.List[str] = None ) -> typing.Tuple[MoveSheetDimensionResp, Response]: return self.cli.raw_request(_gen_move_sheet_dimension_req(request, options)) def prepend_sheet_value( self, request: PrependSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[PrependSheetValueResp, Response]: return self.cli.raw_request(_gen_prepend_sheet_value_req(request, options)) def append_sheet_value( self, request: AppendSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[AppendSheetValueResp, Response]: return self.cli.raw_request(_gen_append_sheet_value_req(request, options)) def insert_sheet_dimension_range( self, request: InsertSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[InsertSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_insert_sheet_dimension_range_req(request, options) ) def add_sheet_dimension_range( self, request: AddSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[AddSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_add_sheet_dimension_range_req(request, options) ) def update_sheet_dimension_range( self, request: UpdateSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_update_sheet_dimension_range_req(request, options) ) def delete_sheet_dimension_range( self, request: DeleteSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_delete_sheet_dimension_range_req(request, options) ) def get_sheet_value( self, request: GetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetValueResp, Response]: return self.cli.raw_request(_gen_get_sheet_value_req(request, options)) def batch_get_sheet_value( self, request: BatchGetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[BatchGetSheetValueResp, Response]: return self.cli.raw_request(_gen_batch_get_sheet_value_req(request, options)) def set_sheet_value( self, request: SetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetValueResp, Response]: return self.cli.raw_request(_gen_set_sheet_value_req(request, options)) def batch_set_sheet_value( self, request: BatchSetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[BatchSetSheetValueResp, Response]: return self.cli.raw_request(_gen_batch_set_sheet_value_req(request, options)) def set_sheet_style( self, request: SetSheetStyleReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetStyleResp, Response]: return self.cli.raw_request(_gen_set_sheet_style_req(request, options)) def batch_set_sheet_style( self, request: BatchSetSheetStyleReq, options: typing.List[str] = None ) -> typing.Tuple[BatchSetSheetStyleResp, Response]: return self.cli.raw_request(_gen_batch_set_sheet_style_req(request, options)) def merge_sheet_cell( self, request: MergeSheetCellReq, options: typing.List[str] = None ) -> typing.Tuple[MergeSheetCellResp, Response]: return self.cli.raw_request(_gen_merge_sheet_cell_req(request, options)) def unmerge_sheet_cell( self, request: UnmergeSheetCellReq, options: typing.List[str] = None ) -> typing.Tuple[UnmergeSheetCellResp, Response]: return self.cli.raw_request(_gen_unmerge_sheet_cell_req(request, options)) def set_sheet_value_image( self, request: SetSheetValueImageReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetValueImageResp, Response]: return self.cli.raw_request(_gen_set_sheet_value_image_req(request, options)) def find_sheet( self, request: FindSheetReq, options: typing.List[str] = None ) -> typing.Tuple[FindSheetResp, Response]: return self.cli.raw_request(_gen_find_sheet_req(request, options)) def replace_sheet( self, request: ReplaceSheetReq, options: typing.List[str] = None ) -> typing.Tuple[ReplaceSheetResp, Response]: return self.cli.raw_request(_gen_replace_sheet_req(request, options)) def create_sheet_condition_format( self, request: CreateSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_create_sheet_condition_format_req(request, options) ) def get_sheet_condition_format( self, request: GetSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_get_sheet_condition_format_req(request, options) ) def update_sheet_condition_format( self, request: UpdateSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_update_sheet_condition_format_req(request, options) ) def delete_sheet_condition_format( self, request: DeleteSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_delete_sheet_condition_format_req(request, options) ) def create_sheet_protected_dimension( self, request: CreateSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_create_sheet_protected_dimension_req(request, options) ) def get_sheet_protected_dimension( self, request: GetSheetProtectedDimensionReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_get_sheet_protected_dimension_req(request, options) ) def update_sheet_protected_dimension( self, request: UpdateSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_update_sheet_protected_dimension_req(request, options) ) def delete_sheet_protected_dimension( self, request: DeleteSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_delete_sheet_protected_dimension_req(request, options) ) def create_sheet_data_validation_dropdown( self, request: CreateSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_create_sheet_data_validation_dropdown_req(request, options) ) def delete_sheet_data_validation_dropdown( self, request: DeleteSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_delete_sheet_data_validation_dropdown_req(request, options) ) def update_sheet_data_validation_dropdown( self, request: UpdateSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_update_sheet_data_validation_dropdown_req(request, options) ) def get_sheet_data_validation_dropdown( self, request: GetSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[GetSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_get_sheet_data_validation_dropdown_req(request, options) ) def create_sheet_filter( self, request: CreateSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFilterResp, Response]: return self.cli.raw_request(_gen_create_sheet_filter_req(request, options)) def delete_sheet_filter( self, request: DeleteSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFilterResp, Response]: return self.cli.raw_request(_gen_delete_sheet_filter_req(request, options)) def update_sheet_filter( self, request: UpdateSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFilterResp, Response]: return self.cli.raw_request(_gen_update_sheet_filter_req(request, options)) def get_sheet_filter( self, request: GetSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterResp, Response]: return self.cli.raw_request(_gen_get_sheet_filter_req(request, options)) def create_sheet_filter_view( self, request: CreateSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_create_sheet_filter_view_req(request, options)) def delete_sheet_filter_view( self, request: DeleteSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_delete_sheet_filter_view_req(request, options)) def update_sheet_filter_view( self, request: UpdateSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_update_sheet_filter_view_req(request, options)) def get_sheet_filter_view( self, request: GetSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_get_sheet_filter_view_req(request, options)) def query_sheet_filter_view( self, request: QuerySheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[QuerySheetFilterViewResp, Response]: return self.cli.raw_request(_gen_query_sheet_filter_view_req(request, options)) def create_sheet_filter_view_condition( self, request: CreateSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_create_sheet_filter_view_condition_req(request, options) ) def delete_sheet_filter_view_condition( self, request: DeleteSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_delete_sheet_filter_view_condition_req(request, options) ) def update_sheet_filter_view_condition( self, request: UpdateSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_update_sheet_filter_view_condition_req(request, options) ) def get_sheet_filter_view_condition( self, request: GetSheetFilterViewConditionReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_get_sheet_filter_view_condition_req(request, options) ) def query_sheet_filter_view_condition( self, request: QuerySheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[QuerySheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_query_sheet_filter_view_condition_req(request, options) ) def create_sheet_float_image( self, request: CreateSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_create_sheet_float_image_req(request, options)) def delete_sheet_float_image( self, request: DeleteSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_delete_sheet_float_image_req(request, options)) def update_sheet_float_image( self, request: UpdateSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_update_sheet_float_image_req(request, options)) def get_sheet_float_image( self, request: GetSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_get_sheet_float_image_req(request, options)) def query_sheet_float_image( self, request: QuerySheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[QuerySheetFloatImageResp, Response]: return self.cli.raw_request(_gen_query_sheet_float_image_req(request, options)) def create_wiki_space( self, request: CreateWikiSpaceReq, options: typing.List[str] = None ) -> typing.Tuple[CreateWikiSpaceResp, Response]: return self.cli.raw_request(_gen_create_wiki_space_req(request, options)) def get_wiki_space_list( self, request: GetWikiSpaceListReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiSpaceListResp, Response]: return self.cli.raw_request(_gen_get_wiki_space_list_req(request, options)) def get_wiki_space( self, request: GetWikiSpaceReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiSpaceResp, Response]: return self.cli.raw_request(_gen_get_wiki_space_req(request, options)) def update_wiki_space_setting( self, request: UpdateWikiSpaceSettingReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateWikiSpaceSettingResp, Response]: return self.cli.raw_request( _gen_update_wiki_space_setting_req(request, options) ) def add_wiki_space_member( self, request: AddWikiSpaceMemberReq, options: typing.List[str] = None ) -> typing.Tuple[AddWikiSpaceMemberResp, Response]: return self.cli.raw_request(_gen_add_wiki_space_member_req(request, options)) def create_wiki_node( self, request: CreateWikiNodeReq, options: typing.List[str] = None ) -> typing.Tuple[CreateWikiNodeResp, Response]: return self.cli.raw_request(_gen_create_wiki_node_req(request, options)) def get_wiki_node_list( self, request: GetWikiNodeListReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiNodeListResp, Response]: return self.cli.raw_request(_gen_get_wiki_node_list_req(request, options)) def get_wiki_node( self, request: GetWikiNodeReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiNodeResp, Response]: return self.cli.raw_request(_gen_get_wiki_node_req(request, options)) def move_docs_to_wiki( self, request: MoveDocsToWikiReq, options: typing.List[str] = None ) -> typing.Tuple[MoveDocsToWikiResp, Response]: return self.cli.raw_request(_gen_move_docs_to_wiki_req(request, options))
pylark/api_service_drive.py
import typing from pylark.lark_request import Response from pylark.api_service_drive_file_search import ( SearchDriveFileReq, SearchDriveFileResp, _gen_search_drive_file_req, ) from pylark.api_service_drive_file_meta_get import ( GetDriveFileMetaReq, GetDriveFileMetaResp, _gen_get_drive_file_meta_req, ) from pylark.api_service_drive_file_create import ( CreateDriveFileReq, CreateDriveFileResp, _gen_create_drive_file_req, ) from pylark.api_service_drive_file_copy import ( CopyDriveFileReq, CopyDriveFileResp, _gen_copy_drive_file_req, ) from pylark.api_service_drive_file_delete import ( DeleteDriveFileReq, DeleteDriveFileResp, _gen_delete_drive_file_req, ) from pylark.api_service_drive_file_sheet_delete import ( DeleteDriveSheetFileReq, DeleteDriveSheetFileResp, _gen_delete_drive_sheet_file_req, ) from pylark.api_service_drive_folder_create import ( CreateDriveFolderReq, CreateDriveFolderResp, _gen_create_drive_folder_req, ) from pylark.api_service_drive_folder_meta import ( GetDriveFolderMetaReq, GetDriveFolderMetaResp, _gen_get_drive_folder_meta_req, ) from pylark.api_service_drive_folder_root_meta import ( GetDriveRootFolderMetaReq, GetDriveRootFolderMetaResp, _gen_get_drive_root_folder_meta_req, ) from pylark.api_service_drive_folder_children_get import ( GetDriveFolderChildrenReq, GetDriveFolderChildrenResp, _gen_get_drive_folder_children_req, ) from pylark.api_service_drive_file_statistics_get import ( GetDriveFileStatisticsReq, GetDriveFileStatisticsResp, _gen_get_drive_file_statistics_req, ) from pylark.api_service_drive_file_download import ( DownloadDriveFileReq, DownloadDriveFileResp, _gen_download_drive_file_req, ) from pylark.api_service_drive_file_upload_all import ( UploadDriveFileReq, UploadDriveFileResp, _gen_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_prepare import ( PrepareUploadDriveFileReq, PrepareUploadDriveFileResp, _gen_prepare_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_part import ( PartUploadDriveFileReq, PartUploadDriveFileResp, _gen_part_upload_drive_file_req, ) from pylark.api_service_drive_file_upload_finish import ( FinishUploadDriveFileReq, FinishUploadDriveFileResp, _gen_finish_upload_drive_file_req, ) from pylark.api_service_drive_media_download import ( DownloadDriveMediaReq, DownloadDriveMediaResp, _gen_download_drive_media_req, ) from pylark.api_service_drive_media_upload_all import ( UploadDriveMediaReq, UploadDriveMediaResp, _gen_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_prepare import ( PrepareUploadDriveMediaReq, PrepareUploadDriveMediaResp, _gen_prepare_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_part import ( PartUploadDriveMediaReq, PartUploadDriveMediaResp, _gen_part_upload_drive_media_req, ) from pylark.api_service_drive_media_upload_finish import ( FinishUploadDriveMediaReq, FinishUploadDriveMediaResp, _gen_finish_upload_drive_media_req, ) from pylark.api_service_drive_permission_member_create_old import ( CreateDriveMemberPermissionOldReq, CreateDriveMemberPermissionOldResp, _gen_create_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_transfer import ( TransferDriveMemberPermissionReq, TransferDriveMemberPermissionResp, _gen_transfer_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_list import ( GetDriveMemberPermissionListReq, GetDriveMemberPermissionListResp, _gen_get_drive_member_permission_list_req, ) from pylark.api_service_drive_permission_member_create import ( CreateDriveMemberPermissionReq, CreateDriveMemberPermissionResp, _gen_create_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_delete_old import ( DeleteDriveMemberPermissionOldReq, DeleteDriveMemberPermissionOldResp, _gen_delete_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_delete import ( DeleteDriveMemberPermissionReq, DeleteDriveMemberPermissionResp, _gen_delete_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_update_old import ( UpdateDriveMemberPermissionOldReq, UpdateDriveMemberPermissionOldResp, _gen_update_drive_member_permission_old_req, ) from pylark.api_service_drive_permission_member_update import ( UpdateDriveMemberPermissionReq, UpdateDriveMemberPermissionResp, _gen_update_drive_member_permission_req, ) from pylark.api_service_drive_permission_member_check import ( CheckDriveMemberPermissionReq, CheckDriveMemberPermissionResp, _gen_check_drive_member_permission_req, ) from pylark.api_service_drive_permission_public_update_v1_old import ( UpdateDrivePublicPermissionV1OldReq, UpdateDrivePublicPermissionV1OldResp, _gen_update_drive_public_permission_v1_old_req, ) from pylark.api_service_drive_permission_public_update_v2_old import ( UpdateDrivePublicPermissionV2OldReq, UpdateDrivePublicPermissionV2OldResp, _gen_update_drive_public_permission_v2_old_req, ) from pylark.api_service_drive_permission_public_get_v2 import ( GetDrivePublicPermissionV2Req, GetDrivePublicPermissionV2Resp, _gen_get_drive_public_permission_v2_req, ) from pylark.api_service_drive_permission_public_patch import ( UpdateDrivePublicPermissionReq, UpdateDrivePublicPermissionResp, _gen_update_drive_public_permission_req, ) from pylark.api_service_drive_media_batch_get_tmp_download_url import ( BatchGetDriveMediaTmpDownloadURLReq, BatchGetDriveMediaTmpDownloadURLResp, _gen_batch_get_drive_media_tmp_download_url_req, ) from pylark.api_service_drive_comment_list import ( GetDriveCommentListReq, GetDriveCommentListResp, _gen_get_drive_comment_list_req, ) from pylark.api_service_drive_comment_get import ( GetDriveCommentReq, GetDriveCommentResp, _gen_get_drive_comment_req, ) from pylark.api_service_drive_comment_create import ( CreateDriveCommentReq, CreateDriveCommentResp, _gen_create_drive_comment_req, ) from pylark.api_service_drive_comment_update import ( UpdateDriveCommentReq, UpdateDriveCommentResp, _gen_update_drive_comment_req, ) from pylark.api_service_drive_comment_delete import ( DeleteDriveCommentReq, DeleteDriveCommentResp, _gen_delete_drive_comment_req, ) from pylark.api_service_drive_comment_patch import ( UpdateDriveCommentPatchReq, UpdateDriveCommentPatchResp, _gen_update_drive_comment_patch_req, ) from pylark.api_service_drive_doc_create import ( CreateDriveDocReq, CreateDriveDocResp, _gen_create_drive_doc_req, ) from pylark.api_service_drive_doc_content_get import ( GetDriveDocContentReq, GetDriveDocContentResp, _gen_get_drive_doc_content_req, ) from pylark.api_service_drive_doc_raw_content_get import ( GetDriveDocRawContentReq, GetDriveDocRawContentResp, _gen_get_drive_doc_raw_content_req, ) from pylark.api_service_drive_doc_meta_get import ( GetDriveDocMetaReq, GetDriveDocMetaResp, _gen_get_drive_doc_meta_req, ) from pylark.api_service_drive_sheet_create import ( CreateSheetReq, CreateSheetResp, _gen_create_sheet_req, ) from pylark.api_service_drive_sheet_meta_get import ( GetSheetMetaReq, GetSheetMetaResp, _gen_get_sheet_meta_req, ) from pylark.api_service_drive_sheet_property_update import ( UpdateSheetPropertyReq, UpdateSheetPropertyResp, _gen_update_sheet_property_req, ) from pylark.api_service_drive_sheet_batch_update import ( BatchUpdateSheetReq, BatchUpdateSheetResp, _gen_batch_update_sheet_req, ) from pylark.api_service_drive_sheet_import import ( ImportSheetReq, ImportSheetResp, _gen_import_sheet_req, ) from pylark.api_service_drive_import_task_create import ( CreateDriveImportTaskReq, CreateDriveImportTaskResp, _gen_create_drive_import_task_req, ) from pylark.api_service_drive_import_task_get import ( GetDriveImportTaskReq, GetDriveImportTaskResp, _gen_get_drive_import_task_req, ) from pylark.api_service_drive_sheet_dimension_move import ( MoveSheetDimensionReq, MoveSheetDimensionResp, _gen_move_sheet_dimension_req, ) from pylark.api_service_drive_sheet_value_prepend import ( PrependSheetValueReq, PrependSheetValueResp, _gen_prepend_sheet_value_req, ) from pylark.api_service_drive_sheet_value_append import ( AppendSheetValueReq, AppendSheetValueResp, _gen_append_sheet_value_req, ) from pylark.api_service_drive_sheet_dimension_range_insert import ( InsertSheetDimensionRangeReq, InsertSheetDimensionRangeResp, _gen_insert_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_add import ( AddSheetDimensionRangeReq, AddSheetDimensionRangeResp, _gen_add_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_update import ( UpdateSheetDimensionRangeReq, UpdateSheetDimensionRangeResp, _gen_update_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_dimension_range_delete import ( DeleteSheetDimensionRangeReq, DeleteSheetDimensionRangeResp, _gen_delete_sheet_dimension_range_req, ) from pylark.api_service_drive_sheet_value_get import ( GetSheetValueReq, GetSheetValueResp, _gen_get_sheet_value_req, ) from pylark.api_service_drive_sheet_value_batch_get import ( BatchGetSheetValueReq, BatchGetSheetValueResp, _gen_batch_get_sheet_value_req, ) from pylark.api_service_drive_sheet_value_set import ( SetSheetValueReq, SetSheetValueResp, _gen_set_sheet_value_req, ) from pylark.api_service_drive_sheet_value_batch_set import ( BatchSetSheetValueReq, BatchSetSheetValueResp, _gen_batch_set_sheet_value_req, ) from pylark.api_service_drive_sheet_style_set import ( SetSheetStyleReq, SetSheetStyleResp, _gen_set_sheet_style_req, ) from pylark.api_service_drive_sheet_style_batch_set import ( BatchSetSheetStyleReq, BatchSetSheetStyleResp, _gen_batch_set_sheet_style_req, ) from pylark.api_service_drive_sheet_cell_merge import ( MergeSheetCellReq, MergeSheetCellResp, _gen_merge_sheet_cell_req, ) from pylark.api_service_drive_sheet_cell_unmerge import ( UnmergeSheetCellReq, UnmergeSheetCellResp, _gen_unmerge_sheet_cell_req, ) from pylark.api_service_drive_sheet_image_set import ( SetSheetValueImageReq, SetSheetValueImageResp, _gen_set_sheet_value_image_req, ) from pylark.api_service_drive_sheet_find import ( FindSheetReq, FindSheetResp, _gen_find_sheet_req, ) from pylark.api_service_drive_sheet_replace import ( ReplaceSheetReq, ReplaceSheetResp, _gen_replace_sheet_req, ) from pylark.api_service_drive_sheet_condition_format_create import ( CreateSheetConditionFormatReq, CreateSheetConditionFormatResp, _gen_create_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_get import ( GetSheetConditionFormatReq, GetSheetConditionFormatResp, _gen_get_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_update import ( UpdateSheetConditionFormatReq, UpdateSheetConditionFormatResp, _gen_update_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_condition_format_delete import ( DeleteSheetConditionFormatReq, DeleteSheetConditionFormatResp, _gen_delete_sheet_condition_format_req, ) from pylark.api_service_drive_sheet_protected_dimension_create import ( CreateSheetProtectedDimensionReq, CreateSheetProtectedDimensionResp, _gen_create_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_get import ( GetSheetProtectedDimensionReq, GetSheetProtectedDimensionResp, _gen_get_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_update import ( UpdateSheetProtectedDimensionReq, UpdateSheetProtectedDimensionResp, _gen_update_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_protected_dimension_delete import ( DeleteSheetProtectedDimensionReq, DeleteSheetProtectedDimensionResp, _gen_delete_sheet_protected_dimension_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_create import ( CreateSheetDataValidationDropdownReq, CreateSheetDataValidationDropdownResp, _gen_create_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_delete import ( DeleteSheetDataValidationDropdownReq, DeleteSheetDataValidationDropdownResp, _gen_delete_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_update import ( UpdateSheetDataValidationDropdownReq, UpdateSheetDataValidationDropdownResp, _gen_update_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_data_validation_dropdown_get import ( GetSheetDataValidationDropdownReq, GetSheetDataValidationDropdownResp, _gen_get_sheet_data_validation_dropdown_req, ) from pylark.api_service_drive_sheet_filter_create import ( CreateSheetFilterReq, CreateSheetFilterResp, _gen_create_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_delete import ( DeleteSheetFilterReq, DeleteSheetFilterResp, _gen_delete_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_update import ( UpdateSheetFilterReq, UpdateSheetFilterResp, _gen_update_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_get import ( GetSheetFilterReq, GetSheetFilterResp, _gen_get_sheet_filter_req, ) from pylark.api_service_drive_sheet_filter_view_create import ( CreateSheetFilterViewReq, CreateSheetFilterViewResp, _gen_create_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_delete import ( DeleteSheetFilterViewReq, DeleteSheetFilterViewResp, _gen_delete_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_update import ( UpdateSheetFilterViewReq, UpdateSheetFilterViewResp, _gen_update_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_get import ( GetSheetFilterViewReq, GetSheetFilterViewResp, _gen_get_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_query import ( QuerySheetFilterViewReq, QuerySheetFilterViewResp, _gen_query_sheet_filter_view_req, ) from pylark.api_service_drive_sheet_filter_view_condition_create import ( CreateSheetFilterViewConditionReq, CreateSheetFilterViewConditionResp, _gen_create_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_delete import ( DeleteSheetFilterViewConditionReq, DeleteSheetFilterViewConditionResp, _gen_delete_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_update import ( UpdateSheetFilterViewConditionReq, UpdateSheetFilterViewConditionResp, _gen_update_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_get import ( GetSheetFilterViewConditionReq, GetSheetFilterViewConditionResp, _gen_get_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_filter_view_condition_query import ( QuerySheetFilterViewConditionReq, QuerySheetFilterViewConditionResp, _gen_query_sheet_filter_view_condition_req, ) from pylark.api_service_drive_sheet_float_image_create import ( CreateSheetFloatImageReq, CreateSheetFloatImageResp, _gen_create_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_delete import ( DeleteSheetFloatImageReq, DeleteSheetFloatImageResp, _gen_delete_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_update import ( UpdateSheetFloatImageReq, UpdateSheetFloatImageResp, _gen_update_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_get import ( GetSheetFloatImageReq, GetSheetFloatImageResp, _gen_get_sheet_float_image_req, ) from pylark.api_service_drive_sheet_float_image_query import ( QuerySheetFloatImageReq, QuerySheetFloatImageResp, _gen_query_sheet_float_image_req, ) from pylark.api_service_drive_wiki_space_create import ( CreateWikiSpaceReq, CreateWikiSpaceResp, _gen_create_wiki_space_req, ) from pylark.api_service_drive_wiki_space_get_list import ( GetWikiSpaceListReq, GetWikiSpaceListResp, _gen_get_wiki_space_list_req, ) from pylark.api_service_drive_wiki_space_get import ( GetWikiSpaceReq, GetWikiSpaceResp, _gen_get_wiki_space_req, ) from pylark.api_service_drive_wiki_space_setting_update import ( UpdateWikiSpaceSettingReq, UpdateWikiSpaceSettingResp, _gen_update_wiki_space_setting_req, ) from pylark.api_service_drive_wiki_space_member_add import ( AddWikiSpaceMemberReq, AddWikiSpaceMemberResp, _gen_add_wiki_space_member_req, ) from pylark.api_service_drive_wiki_node_create import ( CreateWikiNodeReq, CreateWikiNodeResp, _gen_create_wiki_node_req, ) from pylark.api_service_drive_wiki_node_list import ( GetWikiNodeListReq, GetWikiNodeListResp, _gen_get_wiki_node_list_req, ) from pylark.api_service_drive_wiki_node_get import ( GetWikiNodeReq, GetWikiNodeResp, _gen_get_wiki_node_req, ) from pylark.api_service_drive_wiki_move_docs_to_wiki import ( MoveDocsToWikiReq, MoveDocsToWikiResp, _gen_move_docs_to_wiki_req, ) if typing.TYPE_CHECKING: from lark import Lark class LarkDriveService(object): cli: "Lark" def __init__(self, cli: "Lark"): self.cli = cli def search_drive_file( self, request: SearchDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[SearchDriveFileResp, Response]: return self.cli.raw_request(_gen_search_drive_file_req(request, options)) def get_drive_file_meta( self, request: GetDriveFileMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFileMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_file_meta_req(request, options)) def create_drive_file( self, request: CreateDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveFileResp, Response]: return self.cli.raw_request(_gen_create_drive_file_req(request, options)) def copy_drive_file( self, request: CopyDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[CopyDriveFileResp, Response]: return self.cli.raw_request(_gen_copy_drive_file_req(request, options)) def delete_drive_file( self, request: DeleteDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveFileResp, Response]: return self.cli.raw_request(_gen_delete_drive_file_req(request, options)) def delete_drive_sheet_file( self, request: DeleteDriveSheetFileReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveSheetFileResp, Response]: return self.cli.raw_request(_gen_delete_drive_sheet_file_req(request, options)) def create_drive_folder( self, request: CreateDriveFolderReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveFolderResp, Response]: return self.cli.raw_request(_gen_create_drive_folder_req(request, options)) def get_drive_folder_meta( self, request: GetDriveFolderMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFolderMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_folder_meta_req(request, options)) def get_drive_root_folder_meta( self, request: GetDriveRootFolderMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveRootFolderMetaResp, Response]: return self.cli.raw_request( _gen_get_drive_root_folder_meta_req(request, options) ) def get_drive_folder_children( self, request: GetDriveFolderChildrenReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFolderChildrenResp, Response]: return self.cli.raw_request( _gen_get_drive_folder_children_req(request, options) ) def get_drive_file_statistics( self, request: GetDriveFileStatisticsReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveFileStatisticsResp, Response]: return self.cli.raw_request( _gen_get_drive_file_statistics_req(request, options) ) def download_drive_file( self, request: DownloadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[DownloadDriveFileResp, Response]: return self.cli.raw_request(_gen_download_drive_file_req(request, options)) def upload_drive_file( self, request: UploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[UploadDriveFileResp, Response]: return self.cli.raw_request(_gen_upload_drive_file_req(request, options)) def prepare_upload_drive_file( self, request: PrepareUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[PrepareUploadDriveFileResp, Response]: return self.cli.raw_request( _gen_prepare_upload_drive_file_req(request, options) ) def part_upload_drive_file( self, request: PartUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[PartUploadDriveFileResp, Response]: return self.cli.raw_request(_gen_part_upload_drive_file_req(request, options)) def finish_upload_drive_file( self, request: FinishUploadDriveFileReq, options: typing.List[str] = None ) -> typing.Tuple[FinishUploadDriveFileResp, Response]: return self.cli.raw_request(_gen_finish_upload_drive_file_req(request, options)) def download_drive_media( self, request: DownloadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[DownloadDriveMediaResp, Response]: return self.cli.raw_request(_gen_download_drive_media_req(request, options)) def upload_drive_media( self, request: UploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[UploadDriveMediaResp, Response]: return self.cli.raw_request(_gen_upload_drive_media_req(request, options)) def prepare_upload_drive_media( self, request: PrepareUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[PrepareUploadDriveMediaResp, Response]: return self.cli.raw_request( _gen_prepare_upload_drive_media_req(request, options) ) def part_upload_drive_media( self, request: PartUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[PartUploadDriveMediaResp, Response]: return self.cli.raw_request(_gen_part_upload_drive_media_req(request, options)) def finish_upload_drive_media( self, request: FinishUploadDriveMediaReq, options: typing.List[str] = None ) -> typing.Tuple[FinishUploadDriveMediaResp, Response]: return self.cli.raw_request( _gen_finish_upload_drive_media_req(request, options) ) def create_drive_member_permission_old( self, request: CreateDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_create_drive_member_permission_old_req(request, options) ) def transfer_drive_member_permission( self, request: TransferDriveMemberPermissionReq, options: typing.List[str] = None, ) -> typing.Tuple[TransferDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_transfer_drive_member_permission_req(request, options) ) def get_drive_member_permission_list( self, request: GetDriveMemberPermissionListReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveMemberPermissionListResp, Response]: return self.cli.raw_request( _gen_get_drive_member_permission_list_req(request, options) ) def create_drive_member_permission( self, request: CreateDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_create_drive_member_permission_req(request, options) ) def delete_drive_member_permission_old( self, request: DeleteDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_delete_drive_member_permission_old_req(request, options) ) def delete_drive_member_permission( self, request: DeleteDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_delete_drive_member_permission_req(request, options) ) def update_drive_member_permission_old( self, request: UpdateDriveMemberPermissionOldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDriveMemberPermissionOldResp, Response]: return self.cli.raw_request( _gen_update_drive_member_permission_old_req(request, options) ) def update_drive_member_permission( self, request: UpdateDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_update_drive_member_permission_req(request, options) ) def check_drive_member_permission( self, request: CheckDriveMemberPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[CheckDriveMemberPermissionResp, Response]: return self.cli.raw_request( _gen_check_drive_member_permission_req(request, options) ) def update_drive_public_permission_v1_old( self, request: UpdateDrivePublicPermissionV1OldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDrivePublicPermissionV1OldResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_v1_old_req(request, options) ) def update_drive_public_permission_v2_old( self, request: UpdateDrivePublicPermissionV2OldReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateDrivePublicPermissionV2OldResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_v2_old_req(request, options) ) def get_drive_public_permission_v2( self, request: GetDrivePublicPermissionV2Req, options: typing.List[str] = None ) -> typing.Tuple[GetDrivePublicPermissionV2Resp, Response]: return self.cli.raw_request( _gen_get_drive_public_permission_v2_req(request, options) ) def update_drive_public_permission( self, request: UpdateDrivePublicPermissionReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDrivePublicPermissionResp, Response]: return self.cli.raw_request( _gen_update_drive_public_permission_req(request, options) ) def batch_get_drive_media_tmp_download_url( self, request: BatchGetDriveMediaTmpDownloadURLReq, options: typing.List[str] = None, ) -> typing.Tuple[BatchGetDriveMediaTmpDownloadURLResp, Response]: return self.cli.raw_request( _gen_batch_get_drive_media_tmp_download_url_req(request, options) ) def get_drive_comment_list( self, request: GetDriveCommentListReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveCommentListResp, Response]: return self.cli.raw_request(_gen_get_drive_comment_list_req(request, options)) def get_drive_comment( self, request: GetDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveCommentResp, Response]: return self.cli.raw_request(_gen_get_drive_comment_req(request, options)) def create_drive_comment( self, request: CreateDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveCommentResp, Response]: return self.cli.raw_request(_gen_create_drive_comment_req(request, options)) def update_drive_comment( self, request: UpdateDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveCommentResp, Response]: return self.cli.raw_request(_gen_update_drive_comment_req(request, options)) def delete_drive_comment( self, request: DeleteDriveCommentReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteDriveCommentResp, Response]: return self.cli.raw_request(_gen_delete_drive_comment_req(request, options)) def update_drive_comment_patch( self, request: UpdateDriveCommentPatchReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateDriveCommentPatchResp, Response]: return self.cli.raw_request( _gen_update_drive_comment_patch_req(request, options) ) def create_drive_doc( self, request: CreateDriveDocReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveDocResp, Response]: return self.cli.raw_request(_gen_create_drive_doc_req(request, options)) def get_drive_doc_content( self, request: GetDriveDocContentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocContentResp, Response]: return self.cli.raw_request(_gen_get_drive_doc_content_req(request, options)) def get_drive_doc_raw_content( self, request: GetDriveDocRawContentReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocRawContentResp, Response]: return self.cli.raw_request( _gen_get_drive_doc_raw_content_req(request, options) ) def get_drive_doc_meta( self, request: GetDriveDocMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveDocMetaResp, Response]: return self.cli.raw_request(_gen_get_drive_doc_meta_req(request, options)) def create_sheet( self, request: CreateSheetReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetResp, Response]: return self.cli.raw_request(_gen_create_sheet_req(request, options)) def get_sheet_meta( self, request: GetSheetMetaReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetMetaResp, Response]: return self.cli.raw_request(_gen_get_sheet_meta_req(request, options)) def update_sheet_property( self, request: UpdateSheetPropertyReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetPropertyResp, Response]: return self.cli.raw_request(_gen_update_sheet_property_req(request, options)) def batch_update_sheet( self, request: BatchUpdateSheetReq, options: typing.List[str] = None ) -> typing.Tuple[BatchUpdateSheetResp, Response]: return self.cli.raw_request(_gen_batch_update_sheet_req(request, options)) def import_sheet( self, request: ImportSheetReq, options: typing.List[str] = None ) -> typing.Tuple[ImportSheetResp, Response]: return self.cli.raw_request(_gen_import_sheet_req(request, options)) def create_drive_import_task( self, request: CreateDriveImportTaskReq, options: typing.List[str] = None ) -> typing.Tuple[CreateDriveImportTaskResp, Response]: return self.cli.raw_request(_gen_create_drive_import_task_req(request, options)) def get_drive_import_task( self, request: GetDriveImportTaskReq, options: typing.List[str] = None ) -> typing.Tuple[GetDriveImportTaskResp, Response]: return self.cli.raw_request(_gen_get_drive_import_task_req(request, options)) def move_sheet_dimension( self, request: MoveSheetDimensionReq, options: typing.List[str] = None ) -> typing.Tuple[MoveSheetDimensionResp, Response]: return self.cli.raw_request(_gen_move_sheet_dimension_req(request, options)) def prepend_sheet_value( self, request: PrependSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[PrependSheetValueResp, Response]: return self.cli.raw_request(_gen_prepend_sheet_value_req(request, options)) def append_sheet_value( self, request: AppendSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[AppendSheetValueResp, Response]: return self.cli.raw_request(_gen_append_sheet_value_req(request, options)) def insert_sheet_dimension_range( self, request: InsertSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[InsertSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_insert_sheet_dimension_range_req(request, options) ) def add_sheet_dimension_range( self, request: AddSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[AddSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_add_sheet_dimension_range_req(request, options) ) def update_sheet_dimension_range( self, request: UpdateSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_update_sheet_dimension_range_req(request, options) ) def delete_sheet_dimension_range( self, request: DeleteSheetDimensionRangeReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetDimensionRangeResp, Response]: return self.cli.raw_request( _gen_delete_sheet_dimension_range_req(request, options) ) def get_sheet_value( self, request: GetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetValueResp, Response]: return self.cli.raw_request(_gen_get_sheet_value_req(request, options)) def batch_get_sheet_value( self, request: BatchGetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[BatchGetSheetValueResp, Response]: return self.cli.raw_request(_gen_batch_get_sheet_value_req(request, options)) def set_sheet_value( self, request: SetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetValueResp, Response]: return self.cli.raw_request(_gen_set_sheet_value_req(request, options)) def batch_set_sheet_value( self, request: BatchSetSheetValueReq, options: typing.List[str] = None ) -> typing.Tuple[BatchSetSheetValueResp, Response]: return self.cli.raw_request(_gen_batch_set_sheet_value_req(request, options)) def set_sheet_style( self, request: SetSheetStyleReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetStyleResp, Response]: return self.cli.raw_request(_gen_set_sheet_style_req(request, options)) def batch_set_sheet_style( self, request: BatchSetSheetStyleReq, options: typing.List[str] = None ) -> typing.Tuple[BatchSetSheetStyleResp, Response]: return self.cli.raw_request(_gen_batch_set_sheet_style_req(request, options)) def merge_sheet_cell( self, request: MergeSheetCellReq, options: typing.List[str] = None ) -> typing.Tuple[MergeSheetCellResp, Response]: return self.cli.raw_request(_gen_merge_sheet_cell_req(request, options)) def unmerge_sheet_cell( self, request: UnmergeSheetCellReq, options: typing.List[str] = None ) -> typing.Tuple[UnmergeSheetCellResp, Response]: return self.cli.raw_request(_gen_unmerge_sheet_cell_req(request, options)) def set_sheet_value_image( self, request: SetSheetValueImageReq, options: typing.List[str] = None ) -> typing.Tuple[SetSheetValueImageResp, Response]: return self.cli.raw_request(_gen_set_sheet_value_image_req(request, options)) def find_sheet( self, request: FindSheetReq, options: typing.List[str] = None ) -> typing.Tuple[FindSheetResp, Response]: return self.cli.raw_request(_gen_find_sheet_req(request, options)) def replace_sheet( self, request: ReplaceSheetReq, options: typing.List[str] = None ) -> typing.Tuple[ReplaceSheetResp, Response]: return self.cli.raw_request(_gen_replace_sheet_req(request, options)) def create_sheet_condition_format( self, request: CreateSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_create_sheet_condition_format_req(request, options) ) def get_sheet_condition_format( self, request: GetSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_get_sheet_condition_format_req(request, options) ) def update_sheet_condition_format( self, request: UpdateSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_update_sheet_condition_format_req(request, options) ) def delete_sheet_condition_format( self, request: DeleteSheetConditionFormatReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetConditionFormatResp, Response]: return self.cli.raw_request( _gen_delete_sheet_condition_format_req(request, options) ) def create_sheet_protected_dimension( self, request: CreateSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_create_sheet_protected_dimension_req(request, options) ) def get_sheet_protected_dimension( self, request: GetSheetProtectedDimensionReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_get_sheet_protected_dimension_req(request, options) ) def update_sheet_protected_dimension( self, request: UpdateSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_update_sheet_protected_dimension_req(request, options) ) def delete_sheet_protected_dimension( self, request: DeleteSheetProtectedDimensionReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetProtectedDimensionResp, Response]: return self.cli.raw_request( _gen_delete_sheet_protected_dimension_req(request, options) ) def create_sheet_data_validation_dropdown( self, request: CreateSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_create_sheet_data_validation_dropdown_req(request, options) ) def delete_sheet_data_validation_dropdown( self, request: DeleteSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_delete_sheet_data_validation_dropdown_req(request, options) ) def update_sheet_data_validation_dropdown( self, request: UpdateSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_update_sheet_data_validation_dropdown_req(request, options) ) def get_sheet_data_validation_dropdown( self, request: GetSheetDataValidationDropdownReq, options: typing.List[str] = None, ) -> typing.Tuple[GetSheetDataValidationDropdownResp, Response]: return self.cli.raw_request( _gen_get_sheet_data_validation_dropdown_req(request, options) ) def create_sheet_filter( self, request: CreateSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFilterResp, Response]: return self.cli.raw_request(_gen_create_sheet_filter_req(request, options)) def delete_sheet_filter( self, request: DeleteSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFilterResp, Response]: return self.cli.raw_request(_gen_delete_sheet_filter_req(request, options)) def update_sheet_filter( self, request: UpdateSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFilterResp, Response]: return self.cli.raw_request(_gen_update_sheet_filter_req(request, options)) def get_sheet_filter( self, request: GetSheetFilterReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterResp, Response]: return self.cli.raw_request(_gen_get_sheet_filter_req(request, options)) def create_sheet_filter_view( self, request: CreateSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_create_sheet_filter_view_req(request, options)) def delete_sheet_filter_view( self, request: DeleteSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_delete_sheet_filter_view_req(request, options)) def update_sheet_filter_view( self, request: UpdateSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_update_sheet_filter_view_req(request, options)) def get_sheet_filter_view( self, request: GetSheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterViewResp, Response]: return self.cli.raw_request(_gen_get_sheet_filter_view_req(request, options)) def query_sheet_filter_view( self, request: QuerySheetFilterViewReq, options: typing.List[str] = None ) -> typing.Tuple[QuerySheetFilterViewResp, Response]: return self.cli.raw_request(_gen_query_sheet_filter_view_req(request, options)) def create_sheet_filter_view_condition( self, request: CreateSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[CreateSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_create_sheet_filter_view_condition_req(request, options) ) def delete_sheet_filter_view_condition( self, request: DeleteSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[DeleteSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_delete_sheet_filter_view_condition_req(request, options) ) def update_sheet_filter_view_condition( self, request: UpdateSheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[UpdateSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_update_sheet_filter_view_condition_req(request, options) ) def get_sheet_filter_view_condition( self, request: GetSheetFilterViewConditionReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_get_sheet_filter_view_condition_req(request, options) ) def query_sheet_filter_view_condition( self, request: QuerySheetFilterViewConditionReq, options: typing.List[str] = None, ) -> typing.Tuple[QuerySheetFilterViewConditionResp, Response]: return self.cli.raw_request( _gen_query_sheet_filter_view_condition_req(request, options) ) def create_sheet_float_image( self, request: CreateSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[CreateSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_create_sheet_float_image_req(request, options)) def delete_sheet_float_image( self, request: DeleteSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[DeleteSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_delete_sheet_float_image_req(request, options)) def update_sheet_float_image( self, request: UpdateSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_update_sheet_float_image_req(request, options)) def get_sheet_float_image( self, request: GetSheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[GetSheetFloatImageResp, Response]: return self.cli.raw_request(_gen_get_sheet_float_image_req(request, options)) def query_sheet_float_image( self, request: QuerySheetFloatImageReq, options: typing.List[str] = None ) -> typing.Tuple[QuerySheetFloatImageResp, Response]: return self.cli.raw_request(_gen_query_sheet_float_image_req(request, options)) def create_wiki_space( self, request: CreateWikiSpaceReq, options: typing.List[str] = None ) -> typing.Tuple[CreateWikiSpaceResp, Response]: return self.cli.raw_request(_gen_create_wiki_space_req(request, options)) def get_wiki_space_list( self, request: GetWikiSpaceListReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiSpaceListResp, Response]: return self.cli.raw_request(_gen_get_wiki_space_list_req(request, options)) def get_wiki_space( self, request: GetWikiSpaceReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiSpaceResp, Response]: return self.cli.raw_request(_gen_get_wiki_space_req(request, options)) def update_wiki_space_setting( self, request: UpdateWikiSpaceSettingReq, options: typing.List[str] = None ) -> typing.Tuple[UpdateWikiSpaceSettingResp, Response]: return self.cli.raw_request( _gen_update_wiki_space_setting_req(request, options) ) def add_wiki_space_member( self, request: AddWikiSpaceMemberReq, options: typing.List[str] = None ) -> typing.Tuple[AddWikiSpaceMemberResp, Response]: return self.cli.raw_request(_gen_add_wiki_space_member_req(request, options)) def create_wiki_node( self, request: CreateWikiNodeReq, options: typing.List[str] = None ) -> typing.Tuple[CreateWikiNodeResp, Response]: return self.cli.raw_request(_gen_create_wiki_node_req(request, options)) def get_wiki_node_list( self, request: GetWikiNodeListReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiNodeListResp, Response]: return self.cli.raw_request(_gen_get_wiki_node_list_req(request, options)) def get_wiki_node( self, request: GetWikiNodeReq, options: typing.List[str] = None ) -> typing.Tuple[GetWikiNodeResp, Response]: return self.cli.raw_request(_gen_get_wiki_node_req(request, options)) def move_docs_to_wiki( self, request: MoveDocsToWikiReq, options: typing.List[str] = None ) -> typing.Tuple[MoveDocsToWikiResp, Response]: return self.cli.raw_request(_gen_move_docs_to_wiki_req(request, options))
0.227469
0.030416
from itertools import zip_longest import json from plmbr.pipe import pipe from plmbr.pipes import * class validate(Pipe): def __init__(self, *vals): self.vals = vals def pipe(self, items: Iterator) -> Iterator: for expected, actual in zip_longest(self.vals, items): print(f'expecting {expected} got {actual}') assert actual == expected yield actual def test_null(): ( range(3) - null() > validate(0, 1, 2)) def test_json_loads(): items = [{'a': 2}, {'b': 4}] ( (json.dumps(i) for i in items) - json_loads() > validate(*items)) def test_json_dumps(): items = [{'a': 2}, {'b': 4}] ( items - json_dumps() > validate(*[json.dumps(i) for i in items])) def test_batch(): ( range(3) - batch(batch_size=2) > validate([0, 1], [2])) ( [0, 1, 2] - batch(batch_size=2) > validate([0, 1], [2])) def test_unbatch(): ( [range(2), range(3)] - unbatch() > validate(0, 1, 0, 1, 2)) def test_to(): ( range(3) - to(lambda i: i + 1) > validate(1, 2, 3)) def test_keep(): ( range(3) - keep(lambda i: i > 0) > validate(1, 2)) def test_drop_fields(): ( ({'a': i, 'b': i, 'c': i} for i in range(3)) - drop_fields('b', 'c') > validate({'a': 0}, {'a': 1}, {'a': 2})) def test_uniq(): ( ({'a': 0, 'b': i // 2, 'c': i} for i in range(3)) - uniq('a', 'b') > validate( {'a': 0, 'b': 0, 'c': 0}, {'a': 0, 'b': 1, 'c': 2})) def test_sample(): ( range(10) - sample(prob=.5) > validate(1, 4, 8, 9)) def test_window(): ( range(4) - window(size=2) > validate((0, 1), (1, 2), (2, 3))) ( [0, 1, 2, 3] - window(size=2) > validate((0, 1), (1, 2), (2, 3))) def test_append(): res = [8] ( range(4) > append(res) ) assert res == [8, 0, 1, 2, 3] def test_tee(): ( [1, 2, 3] - tee( keep(lambda i: i < 3) - to(lambda i: i * 2), to(lambda i: i * 10)) > validate(2, 4, 10, 20, 30)) def test_catch(): class bad_pipe(Pipe): def pipe(self, items): for i in items: if i % 2: self.throw(i) else: yield i err = [] ( range(5) - bad_pipe() - validate(0, 2, 4) > catch(lambda i: err.append(i)) ) assert err == [1, 3] def test_lambda(): res = [] ( range(3) - to(lambda x: x + 1) - (lambda es: (e + 1 for e in es)) > (lambda es: [res.append(e) for e in es]) ) assert res == [2, 3, 4]
test/test_pipes.py
from itertools import zip_longest import json from plmbr.pipe import pipe from plmbr.pipes import * class validate(Pipe): def __init__(self, *vals): self.vals = vals def pipe(self, items: Iterator) -> Iterator: for expected, actual in zip_longest(self.vals, items): print(f'expecting {expected} got {actual}') assert actual == expected yield actual def test_null(): ( range(3) - null() > validate(0, 1, 2)) def test_json_loads(): items = [{'a': 2}, {'b': 4}] ( (json.dumps(i) for i in items) - json_loads() > validate(*items)) def test_json_dumps(): items = [{'a': 2}, {'b': 4}] ( items - json_dumps() > validate(*[json.dumps(i) for i in items])) def test_batch(): ( range(3) - batch(batch_size=2) > validate([0, 1], [2])) ( [0, 1, 2] - batch(batch_size=2) > validate([0, 1], [2])) def test_unbatch(): ( [range(2), range(3)] - unbatch() > validate(0, 1, 0, 1, 2)) def test_to(): ( range(3) - to(lambda i: i + 1) > validate(1, 2, 3)) def test_keep(): ( range(3) - keep(lambda i: i > 0) > validate(1, 2)) def test_drop_fields(): ( ({'a': i, 'b': i, 'c': i} for i in range(3)) - drop_fields('b', 'c') > validate({'a': 0}, {'a': 1}, {'a': 2})) def test_uniq(): ( ({'a': 0, 'b': i // 2, 'c': i} for i in range(3)) - uniq('a', 'b') > validate( {'a': 0, 'b': 0, 'c': 0}, {'a': 0, 'b': 1, 'c': 2})) def test_sample(): ( range(10) - sample(prob=.5) > validate(1, 4, 8, 9)) def test_window(): ( range(4) - window(size=2) > validate((0, 1), (1, 2), (2, 3))) ( [0, 1, 2, 3] - window(size=2) > validate((0, 1), (1, 2), (2, 3))) def test_append(): res = [8] ( range(4) > append(res) ) assert res == [8, 0, 1, 2, 3] def test_tee(): ( [1, 2, 3] - tee( keep(lambda i: i < 3) - to(lambda i: i * 2), to(lambda i: i * 10)) > validate(2, 4, 10, 20, 30)) def test_catch(): class bad_pipe(Pipe): def pipe(self, items): for i in items: if i % 2: self.throw(i) else: yield i err = [] ( range(5) - bad_pipe() - validate(0, 2, 4) > catch(lambda i: err.append(i)) ) assert err == [1, 3] def test_lambda(): res = [] ( range(3) - to(lambda x: x + 1) - (lambda es: (e + 1 for e in es)) > (lambda es: [res.append(e) for e in es]) ) assert res == [2, 3, 4]
0.518059
0.557424
import os import tkinter as tk import webbrowser from tkinter import messagebox from tkinter import ttk from thonnycontrib.codelive.views.session_status.user_list import UserList, UserListItem SESSION_DIA_MIN_SIZE = {"width": 378, "height": 400} BUG_ICON_PATH = os.path.join(os.path.dirname(__file__), "res", "bug-16.png") BUG_REPORT_URL = "https://github.com/codelive-project/codelive/issues/new" class SessionInfo(ttk.LabelFrame): def __init__(self, parent, session): ttk.LabelFrame.__init__(self, parent, width=100, text="Session Info") # labels frame = ttk.Frame(self) name_label = ttk.Label(frame, text="Your name: ") topic_label = ttk.Label(frame, text="Topic: ") broker_label = ttk.Label(frame, text="Broker: ") driver_label = ttk.Label(frame, text="Driver: ") # feilds connection_info = session.get_connection_info() self.session = session self.driver_name = tk.StringVar() _id, name = session.get_driver() self.driver_name.set(name + " (You)" if self.session.user_id == _id else name) name = ttk.Label(frame, text=session.username) topic = ttk.Label(frame, text=connection_info["topic"]) broker = ttk.Label(frame, text=connection_info["broker"]) driver = ttk.Label(frame, textvariable=self.driver_name) # position name_label.grid(row=0, column=0, sticky=tk.E) topic_label.grid(row=1, column=0, sticky=tk.E) broker_label.grid(row=2, column=0, sticky=tk.E) driver_label.grid(row=3, column=0, sticky=tk.E) name.grid(row=0, column=1, sticky=tk.W) topic.grid(row=1, column=1, sticky=tk.W) broker.grid(row=2, column=1, sticky=tk.W) driver.grid(row=3, column=1, sticky=tk.W) frame.pack(side=tk.TOP, fill=tk.X, expand=True, anchor=tk.CENTER) def update_driver(self, s=None): if s != None: self.driver_name.set(s) else: _id, name = self.session.get_driver() self.driver_name.set( name + " (You)" if self.session.user_id == _id else name ) def update_driver_id(self, _id): name = ( self.session.get_name(_id) + " (You)" if self.session.user_id == _id else self.session.get_name(_id) ) self.driver_name.set(name) class ActionList(ttk.Frame): def __init__(self, parent, session, dia): ttk.Frame.__init__(self, parent) self.dia = dia self.session = session self.request_control = ttk.Button( self, text="Request Control", command=self._request_callback ) leave = ttk.Button(self, text="Leave Session", command=self._leave_callback) self.end = ttk.Button(self, text="End Session", command=self._end_callback) self.request_control.pack( side=tk.LEFT, padx=(5, 0) ) # grid(row = 0, column = 0, columnspan = 2, pady = (5, 2), padx = 10, sticky = tk.N + tk.E + tk.S + tk.W) self.end.pack( side=tk.RIGHT, padx=(0, 0) ) # grid(row = 1, column = 1, pady = (2, 10), padx = (2, 10), sticky = tk.N + tk.E + tk.S + tk.W) leave.pack( side=tk.RIGHT, padx=(0, 5) ) # .grid(row = 1, column = 0, pady = (2, 10), padx = (10, 2), sticky = tk.N + tk.E + tk.S + tk.W) self.request_control["state"] = tk.DISABLED if session.is_host else tk.NORMAL self.end["state"] = tk.NORMAL if session.is_host else tk.DISABLED # configure for resize # self.columnconfigure(0, weight = 1, minsize = 50) # self.columnconfigure(1, weight = 1, minsize = 50) # self.rowconfigure(0, weight = 1, minsize = 10) # self.rowconfigure(1, weight = 1, minsize = 10) self.retry_attempt = 0 def driver(self, val=None): if val == None: return self.end["state"] == tk.NORMAL self.request_control["state"] = tk.DISABLED if val else tk.NORMAL self.end["state"] = tk.NORMAL if val else tk.DISABLED def toggle_driver(self): self.end["state"] = tk.DISABLED if self.end["state"] == tk.NORMAL else tk.NORMAL self.request_control["state"] = ( tk.DISABLED if self.request_control["state"] == tk.NORMAL else tk.NORMAL ) def _request_callback(self): status = self.session.request_control() if status == 0: # Success pass elif status == 1: # Rejected self.retry_attempt += 1 ret = messagebox.askretrycancel( "Request rejected", "Your request was rejected. Do you want to request control again?", ) if ret: if self.retry_attempt >= 5: messagebox.showerror( "Unable to Join", "You cannot request control at the moment. Please try again later.", ) else: self._request_callback() elif status == 2: # out messagebox.showerror( "Request timed-out", "Your request has timed out. Please try again later.", ) else: # general error messagebox.showerror("Error", "Unable to join. Please try again later.") # reset retry attempts after last attempt self.retry_attempt = 0 def _leave_callback(self): ret = self.session.leave() def _end_callback(self): ret = self.session.end() class SessionDialog(tk.Toplevel): def __init__(self, parent, session): tk.Toplevel.__init__(self) self.title("Current Session - Beta") frame = ttk.Frame(self) self.session = session self.session_info = SessionInfo(frame, session) sep1 = ttk.Separator(frame, orient=tk.HORIZONTAL) self.user_list = UserList( frame, session, text="Active Users", borderwidth=1, width=1000 ) sep2 = ttk.Separator(frame, orient=tk.HORIZONTAL) self.buttons = ActionList(frame, session, self) self.session_info.grid( row=0, column=0, sticky=tk.N + tk.E + tk.W, padx=10, pady=5 ) sep1.grid(row=1, column=0, sticky=tk.E + tk.W, padx=10) self.user_list.grid( row=2, column=0, sticky=tk.N + tk.E + tk.S + tk.W, padx=10, pady=(5, 5) ) bug_frame = ttk.Frame(frame) bug_icon = tk.PhotoImage(file=BUG_ICON_PATH) bug = ttk.Button( bug_frame, text="Report Bug", image=bug_icon, compound=tk.LEFT, command=lambda: webbrowser.open(BUG_REPORT_URL), ) bug.image = bug_icon bug.pack(side=tk.RIGHT) bug_frame.grid(row=3, column=0, sticky=tk.E + tk.W, padx=10, pady=(0, 5)) sep2.grid(row=4, column=0, sticky=tk.E + tk.W, padx=10) self.buttons.grid( row=5, column=0, sticky=tk.S + tk.E + tk.W, padx=10, pady=(5, 10) ) frame.pack(fill=tk.BOTH, expand=True) self.protocol("WM_DELETE_WINDOW", self.on_closing) self.minsize(SESSION_DIA_MIN_SIZE["width"], SESSION_DIA_MIN_SIZE["height"]) frame.columnconfigure(0, weight=1) frame.rowconfigure(2, weight=1) self._initial_place(parent) def _initial_place(self, parent): parent_dim, parent_x, parent_y = parent.geometry().split("+") parent_w, parent_h = (int(l) for l in parent_dim.split("x")) parent_x = int(parent_x) parent_y = int(parent_y) screen_width = parent.winfo_screenwidth() screen_height = parent.winfo_screenheight() w, h = SESSION_DIA_MIN_SIZE["width"], SESSION_DIA_MIN_SIZE["height"] _x = _y = None if screen_width < 10 + parent_x + parent_w + w: _x = screen_width - (w + 10) elif parent_x + parent_w < 0: _x = 10 else: _x = 10 + parent_x + parent_w if screen_height < parent_y + h: _y = screen_height - (h + 10) elif parent_y < 0: _y = 10 else: _y = parent_y self.geometry("%dx%d+%d+%d" % (w, h, _x, _y)) def update_host(self, _id=None): self.session_info.update_driver_id(_id) self.user_list.update_driver(_id) self.buttons.driver(self.session.user_id == _id) def add_user(self, user): self.user_list.add_user(user) def remove_id(self, rm_id, new_host=None): self.user_list.remove_id(rm_id) if new_host != None: self.update_host(new_host) def on_closing(self): pass if __name__ == "__main__": import sys import random import string colors = ["#75DBFF", "#50FF56", "#FF8D75", "#FF50AD", "#FF9B47"] class DummyUser: def __init__(self, _id, name=None, is_host=False): self.name = ( name if name != None else str(_id) + " - John " + "".join(random.choice(string.ascii_uppercase) for i in range(10)) ) self.id = _id self.position = "1.1" self.color = random.choice(colors) self.last_alive = 0 self.is_host = is_host self.is_idle = False self.cursor_colored = True class DummySession: def __init__(self, is_host=False): self.user_id = 0 self._users = {i: DummyUser(i) for i in range(1, 10)} self._users[0] = DummyUser(0, "Me", is_host) self.username = "John Doe" self.is_host = is_host if self.is_host == False: self._users[random.randint(1, 9)].is_host = True def get_connection_info(self): return { "name": self.username, "broker": "test_broker", "topic": "test_topic", } def get_driver(self): if self.is_host: return 0, "You" else: for i in self._users: if self._users[i].is_host == True: return i, self._users[i].name return -1, "null" def get_users(self): return self._users def get_name(self, _id): return self._users[_id].name root = tk.Tk() dummyUser = DummyUser( random.randint(0, 9), len(sys.argv) > 2 and sys.argv[2] == "host" ) dummySession = DummySession(len(sys.argv) > 2 and sys.argv[2] == "host") if sys.argv[1] == "dialog": frame = ttk.Frame(root) r = SessionDialog(root, dummySession) text = tk.Text(frame, width=10, height=1) def make_host(): _id = int(text.get("0.0", tk.END).strip()) if r == None: print("Start dialog first") else: r.update_host(_id) button_mh = ttk.Button(frame, text="Make", command=make_host) button_dest = ttk.Button(frame, text="Destroy", command=lambda: r.destroy()) text.grid(row=0, column=0, padx=(10, 2.5), pady=10) button_mh.grid(row=0, column=1, padx=(2.5, 10), pady=(10, 0)) button_dest.grid(row=1, column=1, padx=(2.5, 10), pady=(0, 10)) frame.pack() elif sys.argv[1] == "info": frame = SessionInfo(root, dummySession) frame.pack(padx=50, pady=50) elif sys.argv[1] == "item": frame = UserListItem(root, dummyUser) frame.pack(fill=tk.BOTH, expand=True) def t(): frame.toggle_driver() button = ttk.Button(root, text="Hey", command=t) button.pack() elif sys.argv[1] == "list": frame = UserList(root, dummySession) frame.pack(fill=tk.BOTH, expand=True) t_box = tk.Text(root) t_box.pack(fill=tk.X, expand=True) def add(): global frame name = t_box.get("0.0", tk.END).strip() if len(name) > 0: usr = DummyUser(random.randint(100, 10000000), name) frame.add(usr) def remove(): global frame try: index = int(t_box.get("0.0", tk.END).strip()) frame.remove_id(index) except Exception as e: print(e) ttk.Button(root, text="Add", command=add).pack(fill=tk.X, expand=True) ttk.Button(root, text="Remove", command=remove).pack(fill=tk.X, expand=True) elif sys.argv[1] == "action": frame = ActionList(root, dummySession) frame.pack(fill=tk.X, expand=True) root.mainloop()
thonnycontrib/codelive/views/session_status/dialog.py
import os import tkinter as tk import webbrowser from tkinter import messagebox from tkinter import ttk from thonnycontrib.codelive.views.session_status.user_list import UserList, UserListItem SESSION_DIA_MIN_SIZE = {"width": 378, "height": 400} BUG_ICON_PATH = os.path.join(os.path.dirname(__file__), "res", "bug-16.png") BUG_REPORT_URL = "https://github.com/codelive-project/codelive/issues/new" class SessionInfo(ttk.LabelFrame): def __init__(self, parent, session): ttk.LabelFrame.__init__(self, parent, width=100, text="Session Info") # labels frame = ttk.Frame(self) name_label = ttk.Label(frame, text="Your name: ") topic_label = ttk.Label(frame, text="Topic: ") broker_label = ttk.Label(frame, text="Broker: ") driver_label = ttk.Label(frame, text="Driver: ") # feilds connection_info = session.get_connection_info() self.session = session self.driver_name = tk.StringVar() _id, name = session.get_driver() self.driver_name.set(name + " (You)" if self.session.user_id == _id else name) name = ttk.Label(frame, text=session.username) topic = ttk.Label(frame, text=connection_info["topic"]) broker = ttk.Label(frame, text=connection_info["broker"]) driver = ttk.Label(frame, textvariable=self.driver_name) # position name_label.grid(row=0, column=0, sticky=tk.E) topic_label.grid(row=1, column=0, sticky=tk.E) broker_label.grid(row=2, column=0, sticky=tk.E) driver_label.grid(row=3, column=0, sticky=tk.E) name.grid(row=0, column=1, sticky=tk.W) topic.grid(row=1, column=1, sticky=tk.W) broker.grid(row=2, column=1, sticky=tk.W) driver.grid(row=3, column=1, sticky=tk.W) frame.pack(side=tk.TOP, fill=tk.X, expand=True, anchor=tk.CENTER) def update_driver(self, s=None): if s != None: self.driver_name.set(s) else: _id, name = self.session.get_driver() self.driver_name.set( name + " (You)" if self.session.user_id == _id else name ) def update_driver_id(self, _id): name = ( self.session.get_name(_id) + " (You)" if self.session.user_id == _id else self.session.get_name(_id) ) self.driver_name.set(name) class ActionList(ttk.Frame): def __init__(self, parent, session, dia): ttk.Frame.__init__(self, parent) self.dia = dia self.session = session self.request_control = ttk.Button( self, text="Request Control", command=self._request_callback ) leave = ttk.Button(self, text="Leave Session", command=self._leave_callback) self.end = ttk.Button(self, text="End Session", command=self._end_callback) self.request_control.pack( side=tk.LEFT, padx=(5, 0) ) # grid(row = 0, column = 0, columnspan = 2, pady = (5, 2), padx = 10, sticky = tk.N + tk.E + tk.S + tk.W) self.end.pack( side=tk.RIGHT, padx=(0, 0) ) # grid(row = 1, column = 1, pady = (2, 10), padx = (2, 10), sticky = tk.N + tk.E + tk.S + tk.W) leave.pack( side=tk.RIGHT, padx=(0, 5) ) # .grid(row = 1, column = 0, pady = (2, 10), padx = (10, 2), sticky = tk.N + tk.E + tk.S + tk.W) self.request_control["state"] = tk.DISABLED if session.is_host else tk.NORMAL self.end["state"] = tk.NORMAL if session.is_host else tk.DISABLED # configure for resize # self.columnconfigure(0, weight = 1, minsize = 50) # self.columnconfigure(1, weight = 1, minsize = 50) # self.rowconfigure(0, weight = 1, minsize = 10) # self.rowconfigure(1, weight = 1, minsize = 10) self.retry_attempt = 0 def driver(self, val=None): if val == None: return self.end["state"] == tk.NORMAL self.request_control["state"] = tk.DISABLED if val else tk.NORMAL self.end["state"] = tk.NORMAL if val else tk.DISABLED def toggle_driver(self): self.end["state"] = tk.DISABLED if self.end["state"] == tk.NORMAL else tk.NORMAL self.request_control["state"] = ( tk.DISABLED if self.request_control["state"] == tk.NORMAL else tk.NORMAL ) def _request_callback(self): status = self.session.request_control() if status == 0: # Success pass elif status == 1: # Rejected self.retry_attempt += 1 ret = messagebox.askretrycancel( "Request rejected", "Your request was rejected. Do you want to request control again?", ) if ret: if self.retry_attempt >= 5: messagebox.showerror( "Unable to Join", "You cannot request control at the moment. Please try again later.", ) else: self._request_callback() elif status == 2: # out messagebox.showerror( "Request timed-out", "Your request has timed out. Please try again later.", ) else: # general error messagebox.showerror("Error", "Unable to join. Please try again later.") # reset retry attempts after last attempt self.retry_attempt = 0 def _leave_callback(self): ret = self.session.leave() def _end_callback(self): ret = self.session.end() class SessionDialog(tk.Toplevel): def __init__(self, parent, session): tk.Toplevel.__init__(self) self.title("Current Session - Beta") frame = ttk.Frame(self) self.session = session self.session_info = SessionInfo(frame, session) sep1 = ttk.Separator(frame, orient=tk.HORIZONTAL) self.user_list = UserList( frame, session, text="Active Users", borderwidth=1, width=1000 ) sep2 = ttk.Separator(frame, orient=tk.HORIZONTAL) self.buttons = ActionList(frame, session, self) self.session_info.grid( row=0, column=0, sticky=tk.N + tk.E + tk.W, padx=10, pady=5 ) sep1.grid(row=1, column=0, sticky=tk.E + tk.W, padx=10) self.user_list.grid( row=2, column=0, sticky=tk.N + tk.E + tk.S + tk.W, padx=10, pady=(5, 5) ) bug_frame = ttk.Frame(frame) bug_icon = tk.PhotoImage(file=BUG_ICON_PATH) bug = ttk.Button( bug_frame, text="Report Bug", image=bug_icon, compound=tk.LEFT, command=lambda: webbrowser.open(BUG_REPORT_URL), ) bug.image = bug_icon bug.pack(side=tk.RIGHT) bug_frame.grid(row=3, column=0, sticky=tk.E + tk.W, padx=10, pady=(0, 5)) sep2.grid(row=4, column=0, sticky=tk.E + tk.W, padx=10) self.buttons.grid( row=5, column=0, sticky=tk.S + tk.E + tk.W, padx=10, pady=(5, 10) ) frame.pack(fill=tk.BOTH, expand=True) self.protocol("WM_DELETE_WINDOW", self.on_closing) self.minsize(SESSION_DIA_MIN_SIZE["width"], SESSION_DIA_MIN_SIZE["height"]) frame.columnconfigure(0, weight=1) frame.rowconfigure(2, weight=1) self._initial_place(parent) def _initial_place(self, parent): parent_dim, parent_x, parent_y = parent.geometry().split("+") parent_w, parent_h = (int(l) for l in parent_dim.split("x")) parent_x = int(parent_x) parent_y = int(parent_y) screen_width = parent.winfo_screenwidth() screen_height = parent.winfo_screenheight() w, h = SESSION_DIA_MIN_SIZE["width"], SESSION_DIA_MIN_SIZE["height"] _x = _y = None if screen_width < 10 + parent_x + parent_w + w: _x = screen_width - (w + 10) elif parent_x + parent_w < 0: _x = 10 else: _x = 10 + parent_x + parent_w if screen_height < parent_y + h: _y = screen_height - (h + 10) elif parent_y < 0: _y = 10 else: _y = parent_y self.geometry("%dx%d+%d+%d" % (w, h, _x, _y)) def update_host(self, _id=None): self.session_info.update_driver_id(_id) self.user_list.update_driver(_id) self.buttons.driver(self.session.user_id == _id) def add_user(self, user): self.user_list.add_user(user) def remove_id(self, rm_id, new_host=None): self.user_list.remove_id(rm_id) if new_host != None: self.update_host(new_host) def on_closing(self): pass if __name__ == "__main__": import sys import random import string colors = ["#75DBFF", "#50FF56", "#FF8D75", "#FF50AD", "#FF9B47"] class DummyUser: def __init__(self, _id, name=None, is_host=False): self.name = ( name if name != None else str(_id) + " - John " + "".join(random.choice(string.ascii_uppercase) for i in range(10)) ) self.id = _id self.position = "1.1" self.color = random.choice(colors) self.last_alive = 0 self.is_host = is_host self.is_idle = False self.cursor_colored = True class DummySession: def __init__(self, is_host=False): self.user_id = 0 self._users = {i: DummyUser(i) for i in range(1, 10)} self._users[0] = DummyUser(0, "Me", is_host) self.username = "John Doe" self.is_host = is_host if self.is_host == False: self._users[random.randint(1, 9)].is_host = True def get_connection_info(self): return { "name": self.username, "broker": "test_broker", "topic": "test_topic", } def get_driver(self): if self.is_host: return 0, "You" else: for i in self._users: if self._users[i].is_host == True: return i, self._users[i].name return -1, "null" def get_users(self): return self._users def get_name(self, _id): return self._users[_id].name root = tk.Tk() dummyUser = DummyUser( random.randint(0, 9), len(sys.argv) > 2 and sys.argv[2] == "host" ) dummySession = DummySession(len(sys.argv) > 2 and sys.argv[2] == "host") if sys.argv[1] == "dialog": frame = ttk.Frame(root) r = SessionDialog(root, dummySession) text = tk.Text(frame, width=10, height=1) def make_host(): _id = int(text.get("0.0", tk.END).strip()) if r == None: print("Start dialog first") else: r.update_host(_id) button_mh = ttk.Button(frame, text="Make", command=make_host) button_dest = ttk.Button(frame, text="Destroy", command=lambda: r.destroy()) text.grid(row=0, column=0, padx=(10, 2.5), pady=10) button_mh.grid(row=0, column=1, padx=(2.5, 10), pady=(10, 0)) button_dest.grid(row=1, column=1, padx=(2.5, 10), pady=(0, 10)) frame.pack() elif sys.argv[1] == "info": frame = SessionInfo(root, dummySession) frame.pack(padx=50, pady=50) elif sys.argv[1] == "item": frame = UserListItem(root, dummyUser) frame.pack(fill=tk.BOTH, expand=True) def t(): frame.toggle_driver() button = ttk.Button(root, text="Hey", command=t) button.pack() elif sys.argv[1] == "list": frame = UserList(root, dummySession) frame.pack(fill=tk.BOTH, expand=True) t_box = tk.Text(root) t_box.pack(fill=tk.X, expand=True) def add(): global frame name = t_box.get("0.0", tk.END).strip() if len(name) > 0: usr = DummyUser(random.randint(100, 10000000), name) frame.add(usr) def remove(): global frame try: index = int(t_box.get("0.0", tk.END).strip()) frame.remove_id(index) except Exception as e: print(e) ttk.Button(root, text="Add", command=add).pack(fill=tk.X, expand=True) ttk.Button(root, text="Remove", command=remove).pack(fill=tk.X, expand=True) elif sys.argv[1] == "action": frame = ActionList(root, dummySession) frame.pack(fill=tk.X, expand=True) root.mainloop()
0.405213
0.101411
import optparse import re from pyang import plugin from pyang import util from pyang import grammar def pyang_plugin_init(): plugin.register_plugin(StripPlugin()) class StripPlugin(plugin.PyangPlugin): def add_output_format(self, fmts): fmts['strip'] = self self.handle_comments = True def add_opts(self, optparser): optlist = [ optparse.make_option("--strip-module", type=str, dest="strip_module", help="Colon-separated list of module names to strip out"), optparse.make_option("--strip-yang-canonical", dest="strip_yang_canonical", action="store_true", help="Print in canonical order"), optparse.make_option("--strip-yang-remove-unused-imports", dest="strip_yang_remove_unused_imports", action="store_true"), ] g = optparser.add_option_group("Strip output specific options") g.add_options(optlist) def emit(self, ctx, modules, fd): module = modules[0] ctx.opts.strip_module = ctx.opts.strip_module.split(':') emit_yang(ctx, module, fd) def emit_yang(ctx, module, fd): emit_stmt(ctx, module, fd, 0, None, '', ' ') _force_newline_arg = ('description', 'contact', 'organization') _non_quote_arg_type = ('identifier', 'identifier-ref', 'boolean', 'integer', 'non-negative-integer', 'date', 'ordered-by-arg', 'fraction-digits-arg', 'deviate-arg', 'version', 'status-arg') _kwd_class = { 'yang-version': 'header', 'namespace': 'header', 'prefix': 'header', 'belongs-to': 'header', 'organization': 'meta', 'contact': 'meta', 'description': 'meta', 'reference': 'meta', 'import': 'linkage', 'include': 'linkage', 'revision': 'revision', 'typedef': 'defs', 'grouping': 'defs', 'identity': 'defs', 'feature': 'defs', 'extension': 'defs', '_comment': 'comment', 'module': None, 'submodule': None, } def get_kwd_class(keyword): if util.is_prefixed(keyword): return 'extension' else: try: return _kwd_class[keyword] except KeyError: return 'body' _keyword_with_trailing_newline = ( 'typedef', 'grouping', 'identity', 'feature', 'extension', ) def emit_stmt(ctx, stmt, fd, level, prev_kwd_class, indent, indentstep): if ctx.opts.strip_module and stmt.keyword == 'import' and stmt.arg in ctx.opts.strip_module: return if isinstance(stmt.keyword, tuple): kw_module, _ = stmt.keyword if kw_module in ctx.opts.strip_module: return if ctx.opts.strip_yang_remove_unused_imports and stmt.keyword == 'import': for p in stmt.parent.i_unused_prefixes: if stmt.parent.i_unused_prefixes[p] == stmt: return if util.is_prefixed(stmt.raw_keyword): (prefix, identifier) = stmt.raw_keyword keyword = prefix + ':' + identifier else: keyword = stmt.keyword kwd_class = get_kwd_class(stmt.keyword) if ((level == 1 and kwd_class != prev_kwd_class and kwd_class != 'extension') or stmt.keyword in _keyword_with_trailing_newline): fd.write('\n') if keyword == '_comment': emit_comment(stmt.arg, fd, indent) return fd.write(indent + keyword) if stmt.arg != None: if keyword in grammar.stmt_map: (arg_type, _subspec) = grammar.stmt_map[keyword] if arg_type in _non_quote_arg_type: fd.write(' ' + stmt.arg) else: emit_arg(stmt, fd, indent, indentstep) else: emit_arg(stmt, fd, indent, indentstep) if len(stmt.substmts) == 0: fd.write(';\n') else: fd.write(' {\n') if ctx.opts.strip_yang_canonical: substmts = grammar.sort_canonical(stmt.keyword, stmt.substmts) else: substmts = stmt.substmts if level == 0: kwd_class = 'header' for s in substmts: emit_stmt(ctx, s, fd, level + 1, kwd_class, indent + indentstep, indentstep) kwd_class = get_kwd_class(s.keyword) fd.write(indent + '}\n') def emit_arg(stmt, fd, indent, indentstep): """Heuristically pretty print the argument string""" # current alg. always print a double quoted string arg = stmt.arg arg = arg.replace('\\', r'\\') arg = arg.replace('"', r'\"') arg = arg.replace('\t', r'\t') lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'\n' if stmt.keyword in _force_newline_arg: fd.write('\n' + indent + indentstep + '"' + arg + '"') else: fd.write(' "' + arg + '"') else: fd.write('\n') fd.write(indent + indentstep + '"' + lines[0]) for line in lines[1:-1]: fd.write(indent + indentstep + ' ' + line) # write last line fd.write(indent + indentstep + ' ' + lines[-1]) if lines[-1][-1] == '\n': # last line ends with a newline, indent the ending quote fd.write(indent + indentstep + '"') else: fd.write('"') def emit_comment(comment, fd, indent): lines = comment.splitlines(True) for x in lines: if x[0] == '*': fd.write(indent + ' ' + x) else: fd.write(indent + x) fd.write('\n')
plugins/strip.py
import optparse import re from pyang import plugin from pyang import util from pyang import grammar def pyang_plugin_init(): plugin.register_plugin(StripPlugin()) class StripPlugin(plugin.PyangPlugin): def add_output_format(self, fmts): fmts['strip'] = self self.handle_comments = True def add_opts(self, optparser): optlist = [ optparse.make_option("--strip-module", type=str, dest="strip_module", help="Colon-separated list of module names to strip out"), optparse.make_option("--strip-yang-canonical", dest="strip_yang_canonical", action="store_true", help="Print in canonical order"), optparse.make_option("--strip-yang-remove-unused-imports", dest="strip_yang_remove_unused_imports", action="store_true"), ] g = optparser.add_option_group("Strip output specific options") g.add_options(optlist) def emit(self, ctx, modules, fd): module = modules[0] ctx.opts.strip_module = ctx.opts.strip_module.split(':') emit_yang(ctx, module, fd) def emit_yang(ctx, module, fd): emit_stmt(ctx, module, fd, 0, None, '', ' ') _force_newline_arg = ('description', 'contact', 'organization') _non_quote_arg_type = ('identifier', 'identifier-ref', 'boolean', 'integer', 'non-negative-integer', 'date', 'ordered-by-arg', 'fraction-digits-arg', 'deviate-arg', 'version', 'status-arg') _kwd_class = { 'yang-version': 'header', 'namespace': 'header', 'prefix': 'header', 'belongs-to': 'header', 'organization': 'meta', 'contact': 'meta', 'description': 'meta', 'reference': 'meta', 'import': 'linkage', 'include': 'linkage', 'revision': 'revision', 'typedef': 'defs', 'grouping': 'defs', 'identity': 'defs', 'feature': 'defs', 'extension': 'defs', '_comment': 'comment', 'module': None, 'submodule': None, } def get_kwd_class(keyword): if util.is_prefixed(keyword): return 'extension' else: try: return _kwd_class[keyword] except KeyError: return 'body' _keyword_with_trailing_newline = ( 'typedef', 'grouping', 'identity', 'feature', 'extension', ) def emit_stmt(ctx, stmt, fd, level, prev_kwd_class, indent, indentstep): if ctx.opts.strip_module and stmt.keyword == 'import' and stmt.arg in ctx.opts.strip_module: return if isinstance(stmt.keyword, tuple): kw_module, _ = stmt.keyword if kw_module in ctx.opts.strip_module: return if ctx.opts.strip_yang_remove_unused_imports and stmt.keyword == 'import': for p in stmt.parent.i_unused_prefixes: if stmt.parent.i_unused_prefixes[p] == stmt: return if util.is_prefixed(stmt.raw_keyword): (prefix, identifier) = stmt.raw_keyword keyword = prefix + ':' + identifier else: keyword = stmt.keyword kwd_class = get_kwd_class(stmt.keyword) if ((level == 1 and kwd_class != prev_kwd_class and kwd_class != 'extension') or stmt.keyword in _keyword_with_trailing_newline): fd.write('\n') if keyword == '_comment': emit_comment(stmt.arg, fd, indent) return fd.write(indent + keyword) if stmt.arg != None: if keyword in grammar.stmt_map: (arg_type, _subspec) = grammar.stmt_map[keyword] if arg_type in _non_quote_arg_type: fd.write(' ' + stmt.arg) else: emit_arg(stmt, fd, indent, indentstep) else: emit_arg(stmt, fd, indent, indentstep) if len(stmt.substmts) == 0: fd.write(';\n') else: fd.write(' {\n') if ctx.opts.strip_yang_canonical: substmts = grammar.sort_canonical(stmt.keyword, stmt.substmts) else: substmts = stmt.substmts if level == 0: kwd_class = 'header' for s in substmts: emit_stmt(ctx, s, fd, level + 1, kwd_class, indent + indentstep, indentstep) kwd_class = get_kwd_class(s.keyword) fd.write(indent + '}\n') def emit_arg(stmt, fd, indent, indentstep): """Heuristically pretty print the argument string""" # current alg. always print a double quoted string arg = stmt.arg arg = arg.replace('\\', r'\\') arg = arg.replace('"', r'\"') arg = arg.replace('\t', r'\t') lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'\n' if stmt.keyword in _force_newline_arg: fd.write('\n' + indent + indentstep + '"' + arg + '"') else: fd.write(' "' + arg + '"') else: fd.write('\n') fd.write(indent + indentstep + '"' + lines[0]) for line in lines[1:-1]: fd.write(indent + indentstep + ' ' + line) # write last line fd.write(indent + indentstep + ' ' + lines[-1]) if lines[-1][-1] == '\n': # last line ends with a newline, indent the ending quote fd.write(indent + indentstep + '"') else: fd.write('"') def emit_comment(comment, fd, indent): lines = comment.splitlines(True) for x in lines: if x[0] == '*': fd.write(indent + ' ' + x) else: fd.write(indent + x) fd.write('\n')
0.284477
0.090695
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MerchantBaseEnterOpenModel import MerchantBaseEnterOpenModel from alipay.aop.api.domain.SubMerchantCommonEnterOpenModel import SubMerchantCommonEnterOpenModel from alipay.aop.api.domain.SubMerchantEnterOpenModel import SubMerchantEnterOpenModel class AlipayEbppInvoiceMerchantlistEnterApplyModel(object): def __init__(self): self._merchant_base = None self._sub_merchant_common_info = None self._sub_merchant_list = None @property def merchant_base(self): return self._merchant_base @merchant_base.setter def merchant_base(self, value): if isinstance(value, MerchantBaseEnterOpenModel): self._merchant_base = value else: self._merchant_base = MerchantBaseEnterOpenModel.from_alipay_dict(value) @property def sub_merchant_common_info(self): return self._sub_merchant_common_info @sub_merchant_common_info.setter def sub_merchant_common_info(self, value): if isinstance(value, SubMerchantCommonEnterOpenModel): self._sub_merchant_common_info = value else: self._sub_merchant_common_info = SubMerchantCommonEnterOpenModel.from_alipay_dict(value) @property def sub_merchant_list(self): return self._sub_merchant_list @sub_merchant_list.setter def sub_merchant_list(self, value): if isinstance(value, list): self._sub_merchant_list = list() for i in value: if isinstance(i, SubMerchantEnterOpenModel): self._sub_merchant_list.append(i) else: self._sub_merchant_list.append(SubMerchantEnterOpenModel.from_alipay_dict(i)) def to_alipay_dict(self): params = dict() if self.merchant_base: if hasattr(self.merchant_base, 'to_alipay_dict'): params['merchant_base'] = self.merchant_base.to_alipay_dict() else: params['merchant_base'] = self.merchant_base if self.sub_merchant_common_info: if hasattr(self.sub_merchant_common_info, 'to_alipay_dict'): params['sub_merchant_common_info'] = self.sub_merchant_common_info.to_alipay_dict() else: params['sub_merchant_common_info'] = self.sub_merchant_common_info if self.sub_merchant_list: if isinstance(self.sub_merchant_list, list): for i in range(0, len(self.sub_merchant_list)): element = self.sub_merchant_list[i] if hasattr(element, 'to_alipay_dict'): self.sub_merchant_list[i] = element.to_alipay_dict() if hasattr(self.sub_merchant_list, 'to_alipay_dict'): params['sub_merchant_list'] = self.sub_merchant_list.to_alipay_dict() else: params['sub_merchant_list'] = self.sub_merchant_list return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayEbppInvoiceMerchantlistEnterApplyModel() if 'merchant_base' in d: o.merchant_base = d['merchant_base'] if 'sub_merchant_common_info' in d: o.sub_merchant_common_info = d['sub_merchant_common_info'] if 'sub_merchant_list' in d: o.sub_merchant_list = d['sub_merchant_list'] return o
alipay/aop/api/domain/AlipayEbppInvoiceMerchantlistEnterApplyModel.py
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MerchantBaseEnterOpenModel import MerchantBaseEnterOpenModel from alipay.aop.api.domain.SubMerchantCommonEnterOpenModel import SubMerchantCommonEnterOpenModel from alipay.aop.api.domain.SubMerchantEnterOpenModel import SubMerchantEnterOpenModel class AlipayEbppInvoiceMerchantlistEnterApplyModel(object): def __init__(self): self._merchant_base = None self._sub_merchant_common_info = None self._sub_merchant_list = None @property def merchant_base(self): return self._merchant_base @merchant_base.setter def merchant_base(self, value): if isinstance(value, MerchantBaseEnterOpenModel): self._merchant_base = value else: self._merchant_base = MerchantBaseEnterOpenModel.from_alipay_dict(value) @property def sub_merchant_common_info(self): return self._sub_merchant_common_info @sub_merchant_common_info.setter def sub_merchant_common_info(self, value): if isinstance(value, SubMerchantCommonEnterOpenModel): self._sub_merchant_common_info = value else: self._sub_merchant_common_info = SubMerchantCommonEnterOpenModel.from_alipay_dict(value) @property def sub_merchant_list(self): return self._sub_merchant_list @sub_merchant_list.setter def sub_merchant_list(self, value): if isinstance(value, list): self._sub_merchant_list = list() for i in value: if isinstance(i, SubMerchantEnterOpenModel): self._sub_merchant_list.append(i) else: self._sub_merchant_list.append(SubMerchantEnterOpenModel.from_alipay_dict(i)) def to_alipay_dict(self): params = dict() if self.merchant_base: if hasattr(self.merchant_base, 'to_alipay_dict'): params['merchant_base'] = self.merchant_base.to_alipay_dict() else: params['merchant_base'] = self.merchant_base if self.sub_merchant_common_info: if hasattr(self.sub_merchant_common_info, 'to_alipay_dict'): params['sub_merchant_common_info'] = self.sub_merchant_common_info.to_alipay_dict() else: params['sub_merchant_common_info'] = self.sub_merchant_common_info if self.sub_merchant_list: if isinstance(self.sub_merchant_list, list): for i in range(0, len(self.sub_merchant_list)): element = self.sub_merchant_list[i] if hasattr(element, 'to_alipay_dict'): self.sub_merchant_list[i] = element.to_alipay_dict() if hasattr(self.sub_merchant_list, 'to_alipay_dict'): params['sub_merchant_list'] = self.sub_merchant_list.to_alipay_dict() else: params['sub_merchant_list'] = self.sub_merchant_list return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayEbppInvoiceMerchantlistEnterApplyModel() if 'merchant_base' in d: o.merchant_base = d['merchant_base'] if 'sub_merchant_common_info' in d: o.sub_merchant_common_info = d['sub_merchant_common_info'] if 'sub_merchant_list' in d: o.sub_merchant_list = d['sub_merchant_list'] return o
0.378115
0.040922
import os import sys import time from argparse import ArgumentParser import math import numpy as np import time import torch from torch.optim.lr_scheduler import MultiStepLR import torch.utils.data.distributed from src.model import model, Loss from src.utils import dboxes300_coco, Encoder from src.evaluate import evaluate from src.train import train_loop, tencent_trick from src.data import * # Apex imports try: from apex.parallel.LARC import LARC from apex import amp from apex.fp16_utils import * except ImportError: raise ImportError("Please install APEX from https://github.com/nvidia/apex") class Logger: def __init__(self, batch_size, local_rank, n_gpu, print_freq=20): self.batch_size = batch_size self.local_rank = local_rank self.n_gpu = n_gpu self.print_freq = print_freq self.processed_samples = 0 self.epochs_times = [] self.epochs_speeds = [] def update_iter(self, epoch, iteration, loss): if self.local_rank != 0: return if iteration % self.print_freq == 0: print('Epoch: {:2d}, Iteration: {}, Loss: {}'.format(epoch, iteration, loss)) self.processed_samples = self.processed_samples + self.batch_size def start_epoch(self): self.epoch_start = time.time() def end_epoch(self): epoch_time = time.time() - self.epoch_start epoch_speed = self.processed_samples / epoch_time self.epochs_times.append(epoch_time) self.epochs_speeds.append(epoch_speed) self.processed_samples = 0 if self.local_rank == 0: print('Epoch {:2d} finished. Time: {:4f} s, Speed: {:4f} img/sec, Average speed: {:4f}' .format(len(self.epochs_times)-1, epoch_time, epoch_speed * self.n_gpu, self.average_speed() * self.n_gpu)) def average_speed(self): return sum(self.epochs_speeds) / len(self.epochs_speeds) def make_parser(): parser = ArgumentParser( description="Train Single Shot MultiBox Detector on COCO") parser.add_argument( '--data', '-d', type=str, default='/coco', required=True, help='path to test and training data files') parser.add_argument( '--epochs', '-e', type=int, default=65, help='number of epochs for training') parser.add_argument( '--batch-size', '--bs', type=int, default=32, help='number of examples for each iteration') parser.add_argument( '--eval-batch-size', '--ebs', type=int, default=32, help='number of examples for each evaluation iteration') parser.add_argument( '--seed', '-s', type=int, default=0, help='manually set random seed for torch') parser.add_argument( '--evaluation', nargs='*', type=int, default=[3, 21, 31, 37, 42, 48, 53, 59, 64], help='epochs at which to evaluate') parser.add_argument( '--multistep', nargs='*', type=int, default=[43, 54], help='epochs at which to decay learning rate') parser.add_argument( '--target', type=float, default=None, help='target mAP to assert against at the end') # Hyperparameters parser.add_argument( '--learning-rate', '--lr', type=float, default=2.6e-3, help='learning rate') parser.add_argument( '--momentum', '-m', type=float, default=0.9, help='momentum argument for SGD optimizer') parser.add_argument( '--weight-decay', '--wd', type=float, default=0.0005, help='momentum argument for SGD optimizer') parser.add_argument('--warmup', type=int, default=None) parser.add_argument( '--backbone', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']) parser.add_argument('--num-workers', type=int, default=4) parser.add_argument('--fp16-mode', type=str, default='static', choices=['off', 'static', 'amp'], help='Half precission mode to use') # Distributed parser.add_argument('--local_rank', default=0, type=int, help='Used for multi-process training. Can either be manually set ' + 'or automatically set by using \'python -m multiproc\'.') # Pipeline control parser.add_argument( '--data_pipeline', type=str, default='dali', choices=['dali', 'no_dali'], help='data preprocessing pipline to use') return parser def train(args): if args.amp: amp_handle = amp.init(enabled=args.fp16) args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed: torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.N_gpu = torch.distributed.get_world_size() else: args.N_gpu = 1 dboxes = dboxes300_coco() encoder = Encoder(dboxes) cocoGt = get_coco_ground_truth(args) ssd300 = model(args) args.learning_rate = args.learning_rate * args.N_gpu * (args.batch_size / 32) iteration = 0 loss_func = Loss(dboxes) loss_func.cuda() optimizer = torch.optim.SGD( tencent_trick(ssd300), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay) scheduler = MultiStepLR( optimizer=optimizer, milestones=args.multistep, gamma=0.1) if args.fp16: if args.amp: optimizer = amp_handle.wrap_optimizer(optimizer) else: optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.) val_dataloader, inv_map = get_val_dataloader(args) train_loader = get_train_loader(args, dboxes) acc = 0 logger = Logger(args.batch_size, args.local_rank, args.N_gpu) for epoch in range(0, args.epochs): logger.start_epoch() scheduler.step() iteration = train_loop( ssd300, loss_func, epoch, optimizer, train_loader, iteration, logger, args) logger.end_epoch() if epoch in args.evaluation: acc = evaluate(ssd300, val_dataloader, cocoGt, encoder, inv_map, args) if args.local_rank == 0: print('Epoch {:2d}, Accuracy: {:4f} mAP'.format(epoch, acc)) if args.data_pipeline == 'dali': train_loader.reset() return acc, logger.average_speed() if __name__ == "__main__": parser = make_parser() args = parser.parse_args() if args.local_rank == 0: os.makedirs('./models', exist_ok=True) torch.backends.cudnn.benchmark = True if args.fp16_mode != 'off': args.fp16 = True args.amp = (args.fp16_mode == 'amp') else: args.fp16 = False args.amp = False start_time = time.time() acc, avg_speed = train(args) # avg_speed is reported per node, adjust for the global speed try: num_shards = torch.distributed.get_world_size() except RuntimeError: num_shards = 1 avg_speed = num_shards * avg_speed training_time = time.time() - start_time if args.local_rank == 0: print("Training end: Average speed: {:3f} img/sec, Total time: {:3f} sec, Final accuracy: {:3f} mAP" .format(avg_speed, training_time, acc)) if args.target is not None: if args.target > acc: print('Target mAP of {} not met. Possible regression'.format(args.target)) sys.exit(1)
docs/examples/use_cases/pytorch/single_stage_detector/main.py
import os import sys import time from argparse import ArgumentParser import math import numpy as np import time import torch from torch.optim.lr_scheduler import MultiStepLR import torch.utils.data.distributed from src.model import model, Loss from src.utils import dboxes300_coco, Encoder from src.evaluate import evaluate from src.train import train_loop, tencent_trick from src.data import * # Apex imports try: from apex.parallel.LARC import LARC from apex import amp from apex.fp16_utils import * except ImportError: raise ImportError("Please install APEX from https://github.com/nvidia/apex") class Logger: def __init__(self, batch_size, local_rank, n_gpu, print_freq=20): self.batch_size = batch_size self.local_rank = local_rank self.n_gpu = n_gpu self.print_freq = print_freq self.processed_samples = 0 self.epochs_times = [] self.epochs_speeds = [] def update_iter(self, epoch, iteration, loss): if self.local_rank != 0: return if iteration % self.print_freq == 0: print('Epoch: {:2d}, Iteration: {}, Loss: {}'.format(epoch, iteration, loss)) self.processed_samples = self.processed_samples + self.batch_size def start_epoch(self): self.epoch_start = time.time() def end_epoch(self): epoch_time = time.time() - self.epoch_start epoch_speed = self.processed_samples / epoch_time self.epochs_times.append(epoch_time) self.epochs_speeds.append(epoch_speed) self.processed_samples = 0 if self.local_rank == 0: print('Epoch {:2d} finished. Time: {:4f} s, Speed: {:4f} img/sec, Average speed: {:4f}' .format(len(self.epochs_times)-1, epoch_time, epoch_speed * self.n_gpu, self.average_speed() * self.n_gpu)) def average_speed(self): return sum(self.epochs_speeds) / len(self.epochs_speeds) def make_parser(): parser = ArgumentParser( description="Train Single Shot MultiBox Detector on COCO") parser.add_argument( '--data', '-d', type=str, default='/coco', required=True, help='path to test and training data files') parser.add_argument( '--epochs', '-e', type=int, default=65, help='number of epochs for training') parser.add_argument( '--batch-size', '--bs', type=int, default=32, help='number of examples for each iteration') parser.add_argument( '--eval-batch-size', '--ebs', type=int, default=32, help='number of examples for each evaluation iteration') parser.add_argument( '--seed', '-s', type=int, default=0, help='manually set random seed for torch') parser.add_argument( '--evaluation', nargs='*', type=int, default=[3, 21, 31, 37, 42, 48, 53, 59, 64], help='epochs at which to evaluate') parser.add_argument( '--multistep', nargs='*', type=int, default=[43, 54], help='epochs at which to decay learning rate') parser.add_argument( '--target', type=float, default=None, help='target mAP to assert against at the end') # Hyperparameters parser.add_argument( '--learning-rate', '--lr', type=float, default=2.6e-3, help='learning rate') parser.add_argument( '--momentum', '-m', type=float, default=0.9, help='momentum argument for SGD optimizer') parser.add_argument( '--weight-decay', '--wd', type=float, default=0.0005, help='momentum argument for SGD optimizer') parser.add_argument('--warmup', type=int, default=None) parser.add_argument( '--backbone', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']) parser.add_argument('--num-workers', type=int, default=4) parser.add_argument('--fp16-mode', type=str, default='static', choices=['off', 'static', 'amp'], help='Half precission mode to use') # Distributed parser.add_argument('--local_rank', default=0, type=int, help='Used for multi-process training. Can either be manually set ' + 'or automatically set by using \'python -m multiproc\'.') # Pipeline control parser.add_argument( '--data_pipeline', type=str, default='dali', choices=['dali', 'no_dali'], help='data preprocessing pipline to use') return parser def train(args): if args.amp: amp_handle = amp.init(enabled=args.fp16) args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed: torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.N_gpu = torch.distributed.get_world_size() else: args.N_gpu = 1 dboxes = dboxes300_coco() encoder = Encoder(dboxes) cocoGt = get_coco_ground_truth(args) ssd300 = model(args) args.learning_rate = args.learning_rate * args.N_gpu * (args.batch_size / 32) iteration = 0 loss_func = Loss(dboxes) loss_func.cuda() optimizer = torch.optim.SGD( tencent_trick(ssd300), lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay) scheduler = MultiStepLR( optimizer=optimizer, milestones=args.multistep, gamma=0.1) if args.fp16: if args.amp: optimizer = amp_handle.wrap_optimizer(optimizer) else: optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.) val_dataloader, inv_map = get_val_dataloader(args) train_loader = get_train_loader(args, dboxes) acc = 0 logger = Logger(args.batch_size, args.local_rank, args.N_gpu) for epoch in range(0, args.epochs): logger.start_epoch() scheduler.step() iteration = train_loop( ssd300, loss_func, epoch, optimizer, train_loader, iteration, logger, args) logger.end_epoch() if epoch in args.evaluation: acc = evaluate(ssd300, val_dataloader, cocoGt, encoder, inv_map, args) if args.local_rank == 0: print('Epoch {:2d}, Accuracy: {:4f} mAP'.format(epoch, acc)) if args.data_pipeline == 'dali': train_loader.reset() return acc, logger.average_speed() if __name__ == "__main__": parser = make_parser() args = parser.parse_args() if args.local_rank == 0: os.makedirs('./models', exist_ok=True) torch.backends.cudnn.benchmark = True if args.fp16_mode != 'off': args.fp16 = True args.amp = (args.fp16_mode == 'amp') else: args.fp16 = False args.amp = False start_time = time.time() acc, avg_speed = train(args) # avg_speed is reported per node, adjust for the global speed try: num_shards = torch.distributed.get_world_size() except RuntimeError: num_shards = 1 avg_speed = num_shards * avg_speed training_time = time.time() - start_time if args.local_rank == 0: print("Training end: Average speed: {:3f} img/sec, Total time: {:3f} sec, Final accuracy: {:3f} mAP" .format(avg_speed, training_time, acc)) if args.target is not None: if args.target > acc: print('Target mAP of {} not met. Possible regression'.format(args.target)) sys.exit(1)
0.542621
0.164282
from db import db class PortfolioModel(db.Model): """SQLAlchemy Portfolio Model""" # We assign the correct table __tablename__ = 'portfolios' # Table columns portfolioId = db.Column(db.Integer, primary_key=True, nullable=False) name = db.Column(db.String(300), nullable=False) # Foreign key a portfolio belongs to a user userId = db.Column(db.Integer, db.ForeignKey('users.userId'), nullable=False) # Cascade SQL ALCHEMY # In order to retrieve all portfolio books relations belonging to one portfolio portfolio_books = db.relationship("PortfolioBookModel", cascade="save-update, merge, delete", lazy="dynamic") # We reference the Parent user = db.relationship('UserModel', cascade="save-update") def __init__(self, name, userId): """Constructor of the Portfolio model Arguments: name {string} -- name of the portfolio userId {string} -- id of the parent user """ self.name = name self.userId = userId def json(self): """Return a JSON data of the instance variables""" return {'portfolioId': self.portfolioId ,'portfolioId' : self.portfolioId ,'name': self.name, 'userId': self.userId, 'Portfolio_Book' : [portfolio_book.json() for portfolio_book in self.portfolio_books.all()]} # Important methods used to retrieve data through SQL Alchemy @classmethod def find_by_name(cls, name): """Retrieve the portfolio provided its name""" return cls.query.filter_by(name=name).first() @classmethod def find_by_id(cls, portfolioId): """Retrieve the portfolio provided its id""" return cls.query.filter_by(portfolioId=portfolioId).first() @classmethod def find_portfolios_by_user(cls, userId): """Retrieve the portfolio provided its userId""" return cls.query.filter_by(userId=userId).all() def save_to_db(self): """Methods used to push and commit to the database""" db.session.add(self) db.session.commit() def delete_from_db(self): """Methods used to delete and commit to the database""" db.session.delete(self) db.session.commit()
models/portfolio.py
from db import db class PortfolioModel(db.Model): """SQLAlchemy Portfolio Model""" # We assign the correct table __tablename__ = 'portfolios' # Table columns portfolioId = db.Column(db.Integer, primary_key=True, nullable=False) name = db.Column(db.String(300), nullable=False) # Foreign key a portfolio belongs to a user userId = db.Column(db.Integer, db.ForeignKey('users.userId'), nullable=False) # Cascade SQL ALCHEMY # In order to retrieve all portfolio books relations belonging to one portfolio portfolio_books = db.relationship("PortfolioBookModel", cascade="save-update, merge, delete", lazy="dynamic") # We reference the Parent user = db.relationship('UserModel', cascade="save-update") def __init__(self, name, userId): """Constructor of the Portfolio model Arguments: name {string} -- name of the portfolio userId {string} -- id of the parent user """ self.name = name self.userId = userId def json(self): """Return a JSON data of the instance variables""" return {'portfolioId': self.portfolioId ,'portfolioId' : self.portfolioId ,'name': self.name, 'userId': self.userId, 'Portfolio_Book' : [portfolio_book.json() for portfolio_book in self.portfolio_books.all()]} # Important methods used to retrieve data through SQL Alchemy @classmethod def find_by_name(cls, name): """Retrieve the portfolio provided its name""" return cls.query.filter_by(name=name).first() @classmethod def find_by_id(cls, portfolioId): """Retrieve the portfolio provided its id""" return cls.query.filter_by(portfolioId=portfolioId).first() @classmethod def find_portfolios_by_user(cls, userId): """Retrieve the portfolio provided its userId""" return cls.query.filter_by(userId=userId).all() def save_to_db(self): """Methods used to push and commit to the database""" db.session.add(self) db.session.commit() def delete_from_db(self): """Methods used to delete and commit to the database""" db.session.delete(self) db.session.commit()
0.688364
0.176264
from face_lib import my_api, inference import csv import multiprocessing import tensorflow as tf class LFW_TEST: def __init__(self,sia,se): self.sia = sia self.se = se def csv_write(self,path, data): out_test = open(path, 'w', newline='') csv_test_writer = csv.writer(out_test, dialect='excel') for n in data: x1, x2 = n.get() # 返回图片的128维编码信息 res = self.se.run(self.sia.look_like, feed_dict={self.sia.x1: [x1],self.sia.x2: [x2],self.sia.keep_f: 1.0}) csv_test_writer.writerow([res]) out_test.close() def write(self, Flag,n=3000): lfw_test = my_api.LfwTest() # 获取对象 neg_array = lfw_test.neg_array[:n] pos_array = lfw_test.pos_array[:n] # path_array = lfw_test.path_array neg_data = [] pos_data = [] if Flag == 1 or Flag == 0: # 开启多进程 pool = multiprocessing.Pool(processes=6) for index in neg_array: result = pool.apply_async(lfw_test.get_pair_image, (index,)) neg_data.append(result) pool.close() # 调用join之前,先调用close函数,否则会出错。 pool.join() # 执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束 print("Negative Down!") self.csv_write('./temp/lfw/result/neg.csv', neg_data) print('./temp/lfw/result/neg.csv 写入成功!') if Flag == 2 or Flag == 0: # 开启多进程 pool = multiprocessing.Pool(processes=6) for index in pos_array: result = pool.apply_async(lfw_test.get_pair_image, (index,)) pos_data.append(result) pool.close() # 调用join之前,先调用close函数,否则会出错。 pool.join() # 执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束 print("Positive Down!") self.csv_write('./temp/lfw/result/pos.csv', pos_data) print('./temp/lfw/result/pos.csv 写入成功!') @staticmethod def plot(): # 画图 print('正在绘制图形') lfw_plot = my_api.LfwPlot() lfw_plot.plot() @staticmethod def calculate(): lfw_plot = my_api.LfwPlot() return lfw_plot.calulate() if __name__ == '__main__': size = my_api.size # 图片大小 model_file = 'model/train_faces.model' # 模型存放目录 # # setup siamese network siamese = inference.Siamese(size) sess = tf.Session() saver = tf.train.Saver() # 全局参数初始化 sess.run(tf.global_variables_initializer()) saver.restore(sess, model_file) print('模型重载成功') test = LFW_TEST(siamese,sess) test.write(Flag=0) test.plot() print(test.calculate()) sess.close()
lfw_test.py
from face_lib import my_api, inference import csv import multiprocessing import tensorflow as tf class LFW_TEST: def __init__(self,sia,se): self.sia = sia self.se = se def csv_write(self,path, data): out_test = open(path, 'w', newline='') csv_test_writer = csv.writer(out_test, dialect='excel') for n in data: x1, x2 = n.get() # 返回图片的128维编码信息 res = self.se.run(self.sia.look_like, feed_dict={self.sia.x1: [x1],self.sia.x2: [x2],self.sia.keep_f: 1.0}) csv_test_writer.writerow([res]) out_test.close() def write(self, Flag,n=3000): lfw_test = my_api.LfwTest() # 获取对象 neg_array = lfw_test.neg_array[:n] pos_array = lfw_test.pos_array[:n] # path_array = lfw_test.path_array neg_data = [] pos_data = [] if Flag == 1 or Flag == 0: # 开启多进程 pool = multiprocessing.Pool(processes=6) for index in neg_array: result = pool.apply_async(lfw_test.get_pair_image, (index,)) neg_data.append(result) pool.close() # 调用join之前,先调用close函数,否则会出错。 pool.join() # 执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束 print("Negative Down!") self.csv_write('./temp/lfw/result/neg.csv', neg_data) print('./temp/lfw/result/neg.csv 写入成功!') if Flag == 2 or Flag == 0: # 开启多进程 pool = multiprocessing.Pool(processes=6) for index in pos_array: result = pool.apply_async(lfw_test.get_pair_image, (index,)) pos_data.append(result) pool.close() # 调用join之前,先调用close函数,否则会出错。 pool.join() # 执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束 print("Positive Down!") self.csv_write('./temp/lfw/result/pos.csv', pos_data) print('./temp/lfw/result/pos.csv 写入成功!') @staticmethod def plot(): # 画图 print('正在绘制图形') lfw_plot = my_api.LfwPlot() lfw_plot.plot() @staticmethod def calculate(): lfw_plot = my_api.LfwPlot() return lfw_plot.calulate() if __name__ == '__main__': size = my_api.size # 图片大小 model_file = 'model/train_faces.model' # 模型存放目录 # # setup siamese network siamese = inference.Siamese(size) sess = tf.Session() saver = tf.train.Saver() # 全局参数初始化 sess.run(tf.global_variables_initializer()) saver.restore(sess, model_file) print('模型重载成功') test = LFW_TEST(siamese,sess) test.write(Flag=0) test.plot() print(test.calculate()) sess.close()
0.406273
0.333449
import json from sqlalchemy import text from profiler.domain.aggregation import Aggregation, AggregationBatch from profiler.domain.errors import EntityWasNotStoredError from profiler.ports.aggregations_repository import AggregationsRepository from profiler.db.pg_engine import engine from profiler.utils.json_dumper import dumper class PgAggregationsRepository(AggregationsRepository): def get_aggregation(self, model_name: str, model_version: int) -> Aggregation: with engine.connect() as conn: query = text( """SELECT model_name, batch_name, file_timestamp, aggregation FROM aggregations WHERE model_name=:model_name AND model_version=:model_version""" ).bindparams(model_name=model_name, model_version=model_version) db_rows = conn.execute(query).fetchall() if len(db_rows) == 0: return Aggregation( model_name=model_name, model_version=model_version, features=[], batches=[], ) batches = [] for row in db_rows: ( model_name, batch_name, file_timestamp, raw_aggregation, ) = row batch = AggregationBatch( model_name=model_name, model_version=model_version, batch_name=batch_name, file_timestamp=file_timestamp, feature_statistics=json.loads(raw_aggregation), ) batches.append(batch) return Aggregation( model_name=model_name, model_version=model_version, features=[], batches=batches, ) def save( self, batch: AggregationBatch, ): with engine.connect() as conn: try: conn.execute( text( "INSERT INTO aggregations VALUES (:model_name, :model_version, :batch_name, :file_timestamp, :data, :batch_rows_count)" ).bindparams( model_name=batch.model_name, model_version=batch.model_version, batch_name=batch.batch_name, file_timestamp=batch.file_timestamp, data=json.dumps(batch.feature_statistics, default=dumper), batch_rows_count=0, ), ) except Exception as e: raise EntityWasNotStoredError( f"Aggregation for {batch.model_name}:{batch.model_version}/{batch.batch_name} was not stored", e, )
profiler/profiler/adapters/aggregations_repository/pg_aggregations_repository.py
import json from sqlalchemy import text from profiler.domain.aggregation import Aggregation, AggregationBatch from profiler.domain.errors import EntityWasNotStoredError from profiler.ports.aggregations_repository import AggregationsRepository from profiler.db.pg_engine import engine from profiler.utils.json_dumper import dumper class PgAggregationsRepository(AggregationsRepository): def get_aggregation(self, model_name: str, model_version: int) -> Aggregation: with engine.connect() as conn: query = text( """SELECT model_name, batch_name, file_timestamp, aggregation FROM aggregations WHERE model_name=:model_name AND model_version=:model_version""" ).bindparams(model_name=model_name, model_version=model_version) db_rows = conn.execute(query).fetchall() if len(db_rows) == 0: return Aggregation( model_name=model_name, model_version=model_version, features=[], batches=[], ) batches = [] for row in db_rows: ( model_name, batch_name, file_timestamp, raw_aggregation, ) = row batch = AggregationBatch( model_name=model_name, model_version=model_version, batch_name=batch_name, file_timestamp=file_timestamp, feature_statistics=json.loads(raw_aggregation), ) batches.append(batch) return Aggregation( model_name=model_name, model_version=model_version, features=[], batches=batches, ) def save( self, batch: AggregationBatch, ): with engine.connect() as conn: try: conn.execute( text( "INSERT INTO aggregations VALUES (:model_name, :model_version, :batch_name, :file_timestamp, :data, :batch_rows_count)" ).bindparams( model_name=batch.model_name, model_version=batch.model_version, batch_name=batch.batch_name, file_timestamp=batch.file_timestamp, data=json.dumps(batch.feature_statistics, default=dumper), batch_rows_count=0, ), ) except Exception as e: raise EntityWasNotStoredError( f"Aggregation for {batch.model_name}:{batch.model_version}/{batch.batch_name} was not stored", e, )
0.432183
0.090735
from doit.action import CmdAction from doit.task import clean_targets import sys def gui_open_action(pth): action = None if sys.platform.startswith('linux'): action = ["xdg-open", str(pth)] elif sys.platform.startswith('darwin'): action = ["open", str(pth)] elif sys.platform.startswith('win'): action = ["start", str(pth)] return action def _task_html(pth): """ see http://nbconvert.readthedocs.io/en/latest/usage.html """ return dict( file_dep=[ 'docs/{pth}.ipynb'.format(pth=pth), 'docs/html.tpl'.format(pth=pth), ], # + [ str(p) for p in pathlib.Path('docs/ext_media').glob('*')], targets=[ 'docs/{pth}.html'.format(pth=pth), # 'docs/refs.bib'.format(pth=pth) ], actions=[ # 'mkdir -p docs', # 'ln -f docs/refs.bib docs/'.format(pth=pth), 'jupyter nbconvert --to html ' # '--template=docs/{pth}_html.tpl ' '--TemplateExporter.exclude_output_prompt=True ' '--FilesWriter.build_directory=docs/ ' 'docs/{pth}.ipynb'.format(pth=pth), ], clean=[ # 'rm -rf docs/{pth}_files', clean_targets, ], ) def _task_latex(pth): """ see http://nbconvert.readthedocs.io/en/latest/usage.html """ return dict( file_dep=[ 'docs/{pth}.ipynb'.format(pth=pth), 'docs/{pth}_print.tplx'.format(pth=pth), 'docs/refs.bib'.format(pth=pth), # 'docs/ext_media/', ], targets=[ '_paper_output/{pth}.tex'.format(pth=pth), '_paper_output/refs.bib'.format(pth=pth) ], actions=[ 'mkdir -p _paper_output', 'rm -rf _paper_output/{pth}_files', 'ln -f docs/refs.bib _paper_output'.format(pth=pth), 'jupyter nbconvert --to latex --template=docs/{pth}_print.tplx ' '--FilesWriter.build_directory=_paper_output/ ' '--TemplateExporter.exclude_output_prompt=True ' 'docs/{pth}.ipynb'.format(pth=pth), ], clean=[ 'rm -rf _paper_output/{pth}_files', clean_targets, ], ) def _task_pdf(pth): """ """ return dict( file_dep=[ '_paper_output/refs.bib'.format(pth=pth), '_paper_output/{pth}.tex'.format(pth=pth) ], targets=[ '_paper_output/{pth}.pdf'.format(pth=pth), '_paper_output/{pth}.aux'.format(pth=pth), '_paper_output/{pth}.dvi'.format(pth=pth), '_paper_output/{pth}.bcf'.format(pth=pth), '_paper_output/{pth}.blg'.format(pth=pth), '_paper_output/{pth}.bbl'.format(pth=pth), '_paper_output/{pth}.run.xml'.format(pth=pth), '_paper_output/texput.log', '_paper_output/q.log', ], actions=[ CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'bibtex ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), ], verbosity=1, clean=True, ) def _task_view_pdf(pth): """ """ return dict( file_dep=['_paper_output/{pth}.pdf'.format(pth=pth)], targets=[], actions=[ gui_open_action('_paper_output/{pth}.pdf'.format(pth=pth)), ], ) def _task_zdravko(srcpth, destpth): """ """ return dict( file_dep=[ '_paper_output/{srcpth}.pdf'.format(srcpth=srcpth), '_paper_output/{srcpth}.tex'.format(srcpth=srcpth), '_paper_output/refs.bib' ], actions=[ 'mkdir -p ~/Dropbox/dan-zdravko-stuff/tex/{destpth}/'.format( destpth=destpth ), CmdAction( 'rsync -av {srcpth}_files ' 'refs.bib {srcpth}.tex ' '{srcpth}.pdf' ' ~/Dropbox/dan-zdravko-stuff/tex/{destpth}/'.format( srcpth=srcpth, destpth=destpth ), cwd='_paper_output' ), ], verbosity=2 ) def task_latex_chapter_sparse_hawkes(): return _task_latex('chapter_sparse_hawkes') def task_pdf_chapter_sparse_hawkes(): return _task_pdf('chapter_sparse_hawkes') def task_view_pdf_chapter_sparse_hawkes(): return _task_view_pdf('chapter_sparse_hawkes') def task_zdravko_chapter_sparse_hawkes(): return _task_zdravko('chapter_sparse_hawkes', 'sparse_hawkes') def task_html_chapter_sparse_hawkes(): return _task_html('chapter_sparse_hawkes') def task_html_intro_to_cts_hawkes(): return _task_html('intro_to_cts_hawkes')
dodo.py
from doit.action import CmdAction from doit.task import clean_targets import sys def gui_open_action(pth): action = None if sys.platform.startswith('linux'): action = ["xdg-open", str(pth)] elif sys.platform.startswith('darwin'): action = ["open", str(pth)] elif sys.platform.startswith('win'): action = ["start", str(pth)] return action def _task_html(pth): """ see http://nbconvert.readthedocs.io/en/latest/usage.html """ return dict( file_dep=[ 'docs/{pth}.ipynb'.format(pth=pth), 'docs/html.tpl'.format(pth=pth), ], # + [ str(p) for p in pathlib.Path('docs/ext_media').glob('*')], targets=[ 'docs/{pth}.html'.format(pth=pth), # 'docs/refs.bib'.format(pth=pth) ], actions=[ # 'mkdir -p docs', # 'ln -f docs/refs.bib docs/'.format(pth=pth), 'jupyter nbconvert --to html ' # '--template=docs/{pth}_html.tpl ' '--TemplateExporter.exclude_output_prompt=True ' '--FilesWriter.build_directory=docs/ ' 'docs/{pth}.ipynb'.format(pth=pth), ], clean=[ # 'rm -rf docs/{pth}_files', clean_targets, ], ) def _task_latex(pth): """ see http://nbconvert.readthedocs.io/en/latest/usage.html """ return dict( file_dep=[ 'docs/{pth}.ipynb'.format(pth=pth), 'docs/{pth}_print.tplx'.format(pth=pth), 'docs/refs.bib'.format(pth=pth), # 'docs/ext_media/', ], targets=[ '_paper_output/{pth}.tex'.format(pth=pth), '_paper_output/refs.bib'.format(pth=pth) ], actions=[ 'mkdir -p _paper_output', 'rm -rf _paper_output/{pth}_files', 'ln -f docs/refs.bib _paper_output'.format(pth=pth), 'jupyter nbconvert --to latex --template=docs/{pth}_print.tplx ' '--FilesWriter.build_directory=_paper_output/ ' '--TemplateExporter.exclude_output_prompt=True ' 'docs/{pth}.ipynb'.format(pth=pth), ], clean=[ 'rm -rf _paper_output/{pth}_files', clean_targets, ], ) def _task_pdf(pth): """ """ return dict( file_dep=[ '_paper_output/refs.bib'.format(pth=pth), '_paper_output/{pth}.tex'.format(pth=pth) ], targets=[ '_paper_output/{pth}.pdf'.format(pth=pth), '_paper_output/{pth}.aux'.format(pth=pth), '_paper_output/{pth}.dvi'.format(pth=pth), '_paper_output/{pth}.bcf'.format(pth=pth), '_paper_output/{pth}.blg'.format(pth=pth), '_paper_output/{pth}.bbl'.format(pth=pth), '_paper_output/{pth}.run.xml'.format(pth=pth), '_paper_output/texput.log', '_paper_output/q.log', ], actions=[ CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'bibtex ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), CmdAction( 'pdflatex -halt-on-error -interaction=batchmode ' '{pth}'.format(pth=pth), cwd='_paper_output'), ], verbosity=1, clean=True, ) def _task_view_pdf(pth): """ """ return dict( file_dep=['_paper_output/{pth}.pdf'.format(pth=pth)], targets=[], actions=[ gui_open_action('_paper_output/{pth}.pdf'.format(pth=pth)), ], ) def _task_zdravko(srcpth, destpth): """ """ return dict( file_dep=[ '_paper_output/{srcpth}.pdf'.format(srcpth=srcpth), '_paper_output/{srcpth}.tex'.format(srcpth=srcpth), '_paper_output/refs.bib' ], actions=[ 'mkdir -p ~/Dropbox/dan-zdravko-stuff/tex/{destpth}/'.format( destpth=destpth ), CmdAction( 'rsync -av {srcpth}_files ' 'refs.bib {srcpth}.tex ' '{srcpth}.pdf' ' ~/Dropbox/dan-zdravko-stuff/tex/{destpth}/'.format( srcpth=srcpth, destpth=destpth ), cwd='_paper_output' ), ], verbosity=2 ) def task_latex_chapter_sparse_hawkes(): return _task_latex('chapter_sparse_hawkes') def task_pdf_chapter_sparse_hawkes(): return _task_pdf('chapter_sparse_hawkes') def task_view_pdf_chapter_sparse_hawkes(): return _task_view_pdf('chapter_sparse_hawkes') def task_zdravko_chapter_sparse_hawkes(): return _task_zdravko('chapter_sparse_hawkes', 'sparse_hawkes') def task_html_chapter_sparse_hawkes(): return _task_html('chapter_sparse_hawkes') def task_html_intro_to_cts_hawkes(): return _task_html('intro_to_cts_hawkes')
0.333829
0.079246
# Standard imports from dataclasses import dataclass from typing import List # Third party imports from github.GithubException import UnknownObjectException from requests.exceptions import ReadTimeout # Application imports from app.logger import console from app.techniques.abstract_handler import AbstractHandler from app.entities.repository import Repository class FakeCommits(AbstractHandler): """This technique creates a temporary private Git repository, add fake commits with arbitrary email addresses and it push them on a remote repository. On Github, emails are automatically resolved to Github accounts associated with them. """ repository: Repository = None async def resolve(self, emails: List) -> List: self.repository = Repository() try: console.print("Spoofing email addresses…") await self.repository.create() console.print("{:<40s} {:<10s}".format("Initializing a fake Git repository:", "done")) with console.status("Spoofing email addresses…") as status: for email in emails: self.repository.config(name=email.address, email=email.address) self.repository.add(filename="{}.txt".format(email.address), content=email.address) self.repository.commit(email.address) console.print("{:<40s} {:<10s}".format("Creating fake commits:", "done")) await self.repository.push() console.print("{:<40s} {:<10s}".format("Pushing commits to Github:", "done")) with console.status("Spoofing email addresses…") as status: for commit in self.repository.commits(): if not commit.author: continue for email in emails: if commit.commit.message == email.address: email.user = commit.author break console.print("{:<40s} {:<10s}".format("Resolving email addresses:", "done")) except UnknownObjectException: console.print("{:<40s} [red]{:<10s}[/red]".format( "Spoofing email addresses:", "fail (reason: Github API sends a 404 HTTP code)")) except ReadTimeout: console.print("{:<40s} [red]{:<10s}[/red]".format( "Spoofing email addresses:", "fail (reason: timeout)")) finally: await self.clean() if need_to_be_resolved := list(filter(lambda email: not email.resolved(), emails)): return await super().resolve(need_to_be_resolved) async def clean(self): if self.repository: await self.repository.delete() console.print("{:<40s} {:<10s}".format("Cleaning up the fake repository:", "done"))
email2github/app/techniques/fake_commits.py
# Standard imports from dataclasses import dataclass from typing import List # Third party imports from github.GithubException import UnknownObjectException from requests.exceptions import ReadTimeout # Application imports from app.logger import console from app.techniques.abstract_handler import AbstractHandler from app.entities.repository import Repository class FakeCommits(AbstractHandler): """This technique creates a temporary private Git repository, add fake commits with arbitrary email addresses and it push them on a remote repository. On Github, emails are automatically resolved to Github accounts associated with them. """ repository: Repository = None async def resolve(self, emails: List) -> List: self.repository = Repository() try: console.print("Spoofing email addresses…") await self.repository.create() console.print("{:<40s} {:<10s}".format("Initializing a fake Git repository:", "done")) with console.status("Spoofing email addresses…") as status: for email in emails: self.repository.config(name=email.address, email=email.address) self.repository.add(filename="{}.txt".format(email.address), content=email.address) self.repository.commit(email.address) console.print("{:<40s} {:<10s}".format("Creating fake commits:", "done")) await self.repository.push() console.print("{:<40s} {:<10s}".format("Pushing commits to Github:", "done")) with console.status("Spoofing email addresses…") as status: for commit in self.repository.commits(): if not commit.author: continue for email in emails: if commit.commit.message == email.address: email.user = commit.author break console.print("{:<40s} {:<10s}".format("Resolving email addresses:", "done")) except UnknownObjectException: console.print("{:<40s} [red]{:<10s}[/red]".format( "Spoofing email addresses:", "fail (reason: Github API sends a 404 HTTP code)")) except ReadTimeout: console.print("{:<40s} [red]{:<10s}[/red]".format( "Spoofing email addresses:", "fail (reason: timeout)")) finally: await self.clean() if need_to_be_resolved := list(filter(lambda email: not email.resolved(), emails)): return await super().resolve(need_to_be_resolved) async def clean(self): if self.repository: await self.repository.delete() console.print("{:<40s} {:<10s}".format("Cleaning up the fake repository:", "done"))
0.420005
0.108048
from __future__ import unicode_literals import logging from peewee import fn import time import datetime from fetch.api import make_request, default_requests_session from lock import lock_method from models import SearchResult, WebPageVersion logger = logging.getLogger('data') ARCHIVE_URL = 'http://web.archive.org/cdx/search/cdx' DEFAULT_PARAMS = { 'limit': 50, # default page size for CDX pagination 'output': 'json', 'showResumeKey': 'true', # lightweight pagination of results } REQUEST_DELAY = 1.5 LOCK_FILENAME = '/tmp/histories-fetcher.lock' def get_history(url, fetch_index): params = DEFAULT_PARAMS.copy() params['url'] = url # Flags for controlling paging and scanning results more_results = True watch_for_resume_key = False while more_results: more_results = False response = make_request(default_requests_session.get, ARCHIVE_URL, params=params) time.sleep(REQUEST_DELAY) # Pause so that we don't bombard the server with requests if response is None: break results = response.json() for result_index, result in enumerate(results): # Read the field names from the first result if result_index == 0: field_names = result continue # Resumption key appears after one blank record after the rest of the records # These two lines keep watch for the resumption key and exit the loop once # it has been found. if result == []: watch_for_resume_key = True continue elif watch_for_resume_key: # Setting this parameter advances the page of results for the next query params['resumeKey'] = result[0] more_results = True watch_for_resume_key = False break # If the code has made it this far, this record is a web # page version, and we want to save it. data = dict(zip(field_names, result)) _save_record(url, data, fetch_index) def _save_record(url, record, fetch_index): # Convert string for the timestamp into a proper datetime object try: timestamp_datetime = datetime.datetime.strptime( record['timestamp'], '%Y%m%d%H%M%S', ) except ValueError: logger.warn("Invalid timestamp '%s' for URL %s. Skipping record", record['timestamp'], url) return # We'll create a new record for the version only if it doesn't yet exist. try: WebPageVersion.get( url=url, timestamp=timestamp_datetime, ) except WebPageVersion.DoesNotExist: # In a few exceptional cases, I've found that the length has # the value '-'. We store a null length when we encounter '-'. try: length = int(record['length']) except ValueError: logger.warn("Length '%s' is not an integer for URL %s", record['length'], url) length = None WebPageVersion.create( fetch_index=fetch_index, url=url, url_key=record['urlkey'], timestamp=timestamp_datetime, original=record['original'], mime_type=record['mimetype'], status_code=record['statuscode'], digest=record['digest'], length=length, ) @lock_method(LOCK_FILENAME) def main(*args, **kwargs): # Create a new fetch index. last_fetch_index = WebPageVersion.select(fn.Max(WebPageVersion.fetch_index)).scalar() or 0 fetch_index = last_fetch_index + 1 search_results = SearchResult.select(SearchResult.url).distinct() for search_result in search_results: get_history(search_result.url, fetch_index) def configure_parser(parser): parser.description = "Get Internet Archive histories for all stored search results."
fetch/histories.py
from __future__ import unicode_literals import logging from peewee import fn import time import datetime from fetch.api import make_request, default_requests_session from lock import lock_method from models import SearchResult, WebPageVersion logger = logging.getLogger('data') ARCHIVE_URL = 'http://web.archive.org/cdx/search/cdx' DEFAULT_PARAMS = { 'limit': 50, # default page size for CDX pagination 'output': 'json', 'showResumeKey': 'true', # lightweight pagination of results } REQUEST_DELAY = 1.5 LOCK_FILENAME = '/tmp/histories-fetcher.lock' def get_history(url, fetch_index): params = DEFAULT_PARAMS.copy() params['url'] = url # Flags for controlling paging and scanning results more_results = True watch_for_resume_key = False while more_results: more_results = False response = make_request(default_requests_session.get, ARCHIVE_URL, params=params) time.sleep(REQUEST_DELAY) # Pause so that we don't bombard the server with requests if response is None: break results = response.json() for result_index, result in enumerate(results): # Read the field names from the first result if result_index == 0: field_names = result continue # Resumption key appears after one blank record after the rest of the records # These two lines keep watch for the resumption key and exit the loop once # it has been found. if result == []: watch_for_resume_key = True continue elif watch_for_resume_key: # Setting this parameter advances the page of results for the next query params['resumeKey'] = result[0] more_results = True watch_for_resume_key = False break # If the code has made it this far, this record is a web # page version, and we want to save it. data = dict(zip(field_names, result)) _save_record(url, data, fetch_index) def _save_record(url, record, fetch_index): # Convert string for the timestamp into a proper datetime object try: timestamp_datetime = datetime.datetime.strptime( record['timestamp'], '%Y%m%d%H%M%S', ) except ValueError: logger.warn("Invalid timestamp '%s' for URL %s. Skipping record", record['timestamp'], url) return # We'll create a new record for the version only if it doesn't yet exist. try: WebPageVersion.get( url=url, timestamp=timestamp_datetime, ) except WebPageVersion.DoesNotExist: # In a few exceptional cases, I've found that the length has # the value '-'. We store a null length when we encounter '-'. try: length = int(record['length']) except ValueError: logger.warn("Length '%s' is not an integer for URL %s", record['length'], url) length = None WebPageVersion.create( fetch_index=fetch_index, url=url, url_key=record['urlkey'], timestamp=timestamp_datetime, original=record['original'], mime_type=record['mimetype'], status_code=record['statuscode'], digest=record['digest'], length=length, ) @lock_method(LOCK_FILENAME) def main(*args, **kwargs): # Create a new fetch index. last_fetch_index = WebPageVersion.select(fn.Max(WebPageVersion.fetch_index)).scalar() or 0 fetch_index = last_fetch_index + 1 search_results = SearchResult.select(SearchResult.url).distinct() for search_result in search_results: get_history(search_result.url, fetch_index) def configure_parser(parser): parser.description = "Get Internet Archive histories for all stored search results."
0.483892
0.10217
from unittest.mock import MagicMock, call, mock_open, patch from pytest import raises from vang.pio.rsr import _in from vang.pio.rsr import _replace_in_file from vang.pio.rsr import _replace_file from vang.pio.rsr import _rsr from vang.pio.rsr import get_replace_function from vang.pio.rsr import rsr from vang.pio.rsr import main from vang.pio.rsr import parse_args import pytest def test_get_replace_function(): assert 'Hello#World' == get_replace_function(False)('Hello.World', '.', '#') assert '###########' == get_replace_function(True)('Hello.World', '.', '#') @patch('vang.pio.rsr.remove') @patch('vang.pio.rsr.replace') def test__replace_in_file(mock_replace, mock_remove): with patch('vang.pio.rsr.open', mock_open(), create=True) as m: old_file = MagicMock() old_file.__enter__.return_value.__iter__.return_value = [ '\n'.join(['foo.bar'] * 10) ] old_file.__exit__.return_value = False new_file = MagicMock() new_file.__exit__.return_value = False m.side_effect = (old_file, new_file) _replace_in_file('.', '#', 'path', get_replace_function(True)) assert [call('path.tmp', 'path')] == mock_replace.mock_calls assert [] == mock_remove.mock_calls assert [ call('path', 'tr', encoding='UTF-8', errors='ignore'), call('path.tmp', 'tw', encoding='UTF-8') ] == m.mock_calls assert [ call.__enter__(), call.__enter__().write( '#######\n#######\n#######\n#######\n#######\n' '#######\n#######\n#######\n#######\n#######'), call.__exit__(None, None, None) ] == new_file.mock_calls @pytest.mark.parametrize("file, expected", [ ('foox', [call('path/foox', 'path/barx')]), ('baz', []), ]) @patch('vang.pio.rsr.rename') def test__replace_file(mock_rename, file, expected): _replace_file('foo', 'bar', 'path', file, get_replace_function(False)) assert expected == mock_rename.mock_calls @pytest.mark.parametrize("name, expected", [ ('foo', True), ('bar', True), ('.o.', True), ('baz', False), ('.o', False), ]) def test__in(name, expected): assert expected == _in(name, ['foo', 'bar']) @patch('vang.pio.rsr.walk', autospec=True) @patch('vang.pio.rsr._replace_in_file', autospec=True) @patch('vang.pio.rsr._replace_file', autospec=True) def test__rsr(mock__replace_file, mock__replace_in_file, mock_walk): mock_walk.return_value = [ ('/old', ('older', '.git'), ('baz', '.gitignore')), ('/old/older', (), ('oldest', 'eggs')), ('/old/.git', (), ('oldest', 'eggs')), ] def replace_function(x, y, z): pass _rsr( 'root', ['.git', '.gitignore', 'target'], 'old', 'new', replace_function, ) assert [call('root', False)] == mock_walk.mock_calls assert [ call('old', 'new', '/old', 'baz', replace_function), call('old', 'new', '/old', 'older', replace_function), call('old', 'new', '/old/older', 'oldest', replace_function), call('old', 'new', '/old/older', 'eggs', replace_function) ] == mock__replace_file.mock_calls assert [ call('old', 'new', '/old/baz', replace_function), call('old', 'new', '/old/older/oldest', replace_function), call('old', 'new', '/old/older/eggs', replace_function) ] == mock__replace_in_file.mock_calls @patch('vang.pio.rsr._rsr', autospec=True) def test_rsr(mock__rsr): rsr('old', 'new', ['d1', 'd2'], 'rf') assert [ call('d1', ['.git', '.gitignore', 'target'], 'old', 'new', 'rf'), call('d2', ['.git', '.gitignore', 'target'], 'old', 'new', 'rf') ] == mock__rsr.mock_calls @patch('vang.pio.rsr.get_replace_function', autospec=True) @patch('vang.pio.rsr.rsr', autospec=True) def test_main(mock_rsr, mock_get_replace_function): mock_get_replace_function.return_value = 'rf' main('old', 'new', ['d1', 'd2'], True) assert [call(True)] == mock_get_replace_function.mock_calls assert [call('old', 'new', ['d1', 'd2'], 'rf')] == mock_rsr.mock_calls @pytest.mark.parametrize("args", [ '', '1 2 3', ]) def test_parse_args_raises(args): with raises(SystemExit): parse_args(args.split(' ') if args else args) @pytest.mark.parametrize("args, expected", [ ['old new', { 'old': 'old', 'new': 'new', 'dirs': ['.'], 'regexp': False }], [ 'old new -d d1 d2 -r', { 'old': 'old', 'new': 'new', 'dirs': ['d1', 'd2'], 'regexp': True } ], ]) def test_parse_args_valid(args, expected): assert expected == parse_args(args.split(' ')).__dict__
vang/pio/tests/test_rsr.py
from unittest.mock import MagicMock, call, mock_open, patch from pytest import raises from vang.pio.rsr import _in from vang.pio.rsr import _replace_in_file from vang.pio.rsr import _replace_file from vang.pio.rsr import _rsr from vang.pio.rsr import get_replace_function from vang.pio.rsr import rsr from vang.pio.rsr import main from vang.pio.rsr import parse_args import pytest def test_get_replace_function(): assert 'Hello#World' == get_replace_function(False)('Hello.World', '.', '#') assert '###########' == get_replace_function(True)('Hello.World', '.', '#') @patch('vang.pio.rsr.remove') @patch('vang.pio.rsr.replace') def test__replace_in_file(mock_replace, mock_remove): with patch('vang.pio.rsr.open', mock_open(), create=True) as m: old_file = MagicMock() old_file.__enter__.return_value.__iter__.return_value = [ '\n'.join(['foo.bar'] * 10) ] old_file.__exit__.return_value = False new_file = MagicMock() new_file.__exit__.return_value = False m.side_effect = (old_file, new_file) _replace_in_file('.', '#', 'path', get_replace_function(True)) assert [call('path.tmp', 'path')] == mock_replace.mock_calls assert [] == mock_remove.mock_calls assert [ call('path', 'tr', encoding='UTF-8', errors='ignore'), call('path.tmp', 'tw', encoding='UTF-8') ] == m.mock_calls assert [ call.__enter__(), call.__enter__().write( '#######\n#######\n#######\n#######\n#######\n' '#######\n#######\n#######\n#######\n#######'), call.__exit__(None, None, None) ] == new_file.mock_calls @pytest.mark.parametrize("file, expected", [ ('foox', [call('path/foox', 'path/barx')]), ('baz', []), ]) @patch('vang.pio.rsr.rename') def test__replace_file(mock_rename, file, expected): _replace_file('foo', 'bar', 'path', file, get_replace_function(False)) assert expected == mock_rename.mock_calls @pytest.mark.parametrize("name, expected", [ ('foo', True), ('bar', True), ('.o.', True), ('baz', False), ('.o', False), ]) def test__in(name, expected): assert expected == _in(name, ['foo', 'bar']) @patch('vang.pio.rsr.walk', autospec=True) @patch('vang.pio.rsr._replace_in_file', autospec=True) @patch('vang.pio.rsr._replace_file', autospec=True) def test__rsr(mock__replace_file, mock__replace_in_file, mock_walk): mock_walk.return_value = [ ('/old', ('older', '.git'), ('baz', '.gitignore')), ('/old/older', (), ('oldest', 'eggs')), ('/old/.git', (), ('oldest', 'eggs')), ] def replace_function(x, y, z): pass _rsr( 'root', ['.git', '.gitignore', 'target'], 'old', 'new', replace_function, ) assert [call('root', False)] == mock_walk.mock_calls assert [ call('old', 'new', '/old', 'baz', replace_function), call('old', 'new', '/old', 'older', replace_function), call('old', 'new', '/old/older', 'oldest', replace_function), call('old', 'new', '/old/older', 'eggs', replace_function) ] == mock__replace_file.mock_calls assert [ call('old', 'new', '/old/baz', replace_function), call('old', 'new', '/old/older/oldest', replace_function), call('old', 'new', '/old/older/eggs', replace_function) ] == mock__replace_in_file.mock_calls @patch('vang.pio.rsr._rsr', autospec=True) def test_rsr(mock__rsr): rsr('old', 'new', ['d1', 'd2'], 'rf') assert [ call('d1', ['.git', '.gitignore', 'target'], 'old', 'new', 'rf'), call('d2', ['.git', '.gitignore', 'target'], 'old', 'new', 'rf') ] == mock__rsr.mock_calls @patch('vang.pio.rsr.get_replace_function', autospec=True) @patch('vang.pio.rsr.rsr', autospec=True) def test_main(mock_rsr, mock_get_replace_function): mock_get_replace_function.return_value = 'rf' main('old', 'new', ['d1', 'd2'], True) assert [call(True)] == mock_get_replace_function.mock_calls assert [call('old', 'new', ['d1', 'd2'], 'rf')] == mock_rsr.mock_calls @pytest.mark.parametrize("args", [ '', '1 2 3', ]) def test_parse_args_raises(args): with raises(SystemExit): parse_args(args.split(' ') if args else args) @pytest.mark.parametrize("args, expected", [ ['old new', { 'old': 'old', 'new': 'new', 'dirs': ['.'], 'regexp': False }], [ 'old new -d d1 d2 -r', { 'old': 'old', 'new': 'new', 'dirs': ['d1', 'd2'], 'regexp': True } ], ]) def test_parse_args_valid(args, expected): assert expected == parse_args(args.split(' ')).__dict__
0.452052
0.366533
import logging import os import re from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import pandas as pd from .util import print_log, read_fasta_and_generate_seq def create_bed_from_fa(fa_path, dest_dir_path, bgzip='bgzip', human_autosome=False, target_letters='ACGT', n_cpu=1): logger = logging.getLogger(__name__) target_letter_set = set(target_letters) print_log('Set target letters:\t{}'.format(target_letter_set)) fa = Path(fa_path).resolve() assert fa.is_file(), f'file not found: {fa}' bed = Path(dest_dir_path).resolve().joinpath( re.sub(r'\.(gz|bz2|bgz)', '', Path(fa_path).name) + ('.autosome.' if human_autosome else '.') + ''.join(sorted(list(target_letter_set))) + '.bed' ) autosomes = {f'chr{i}' for i in range(1, 23)} fs = list() with ProcessPoolExecutor(max_workers=n_cpu) as x: for chrom, seq in read_fasta_and_generate_seq(path=str(fa)): seq_len = len(seq) if human_autosome and chrom in autosomes: print_log( f'Detect the target letters:\t{chrom}\t({seq_len} bp)' ) fs.append( x.submit( _identify_target_region, chrom, seq, target_letter_set ) ) else: logger.info(f'Skip detection: {chrom} ({seq_len} bp)') f_results = [f.result() for f in as_completed(fs)] df_bed = pd.concat( f_results, ignore_index=True, sort=False ).sort_values(['chrom', 'chromStart', 'chromEnd']) logger.debug(f'df_bed:{os.linesep}{df_bed}') print_log(f'Write a BED file:\t{bed}') df_bed.to_csv(bed, sep='\t', header=False, index=False) def _identify_target_region(chrom, sequence, target_letter_set): bseq = pd.Series(list(sequence)).isin(target_letter_set).astype(int) if bseq.sum() > 0: return bseq.pipe( lambda s: pd.DataFrame({ 'chrom': chrom, 'chromStart': [ *([0] if s.iloc[0] == 1 else list()), *s[s.diff() == 1].index ], 'chromEnd': [ *s[s.diff() == -1].index, *([len(s)] if s.iloc[-1] == 1 else list()) ] }) ) else: logger = logging.getLogger(__name__) logger.info(f'Target letters not detected: {chrom}')
tmber/bed.py
import logging import os import re from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import pandas as pd from .util import print_log, read_fasta_and_generate_seq def create_bed_from_fa(fa_path, dest_dir_path, bgzip='bgzip', human_autosome=False, target_letters='ACGT', n_cpu=1): logger = logging.getLogger(__name__) target_letter_set = set(target_letters) print_log('Set target letters:\t{}'.format(target_letter_set)) fa = Path(fa_path).resolve() assert fa.is_file(), f'file not found: {fa}' bed = Path(dest_dir_path).resolve().joinpath( re.sub(r'\.(gz|bz2|bgz)', '', Path(fa_path).name) + ('.autosome.' if human_autosome else '.') + ''.join(sorted(list(target_letter_set))) + '.bed' ) autosomes = {f'chr{i}' for i in range(1, 23)} fs = list() with ProcessPoolExecutor(max_workers=n_cpu) as x: for chrom, seq in read_fasta_and_generate_seq(path=str(fa)): seq_len = len(seq) if human_autosome and chrom in autosomes: print_log( f'Detect the target letters:\t{chrom}\t({seq_len} bp)' ) fs.append( x.submit( _identify_target_region, chrom, seq, target_letter_set ) ) else: logger.info(f'Skip detection: {chrom} ({seq_len} bp)') f_results = [f.result() for f in as_completed(fs)] df_bed = pd.concat( f_results, ignore_index=True, sort=False ).sort_values(['chrom', 'chromStart', 'chromEnd']) logger.debug(f'df_bed:{os.linesep}{df_bed}') print_log(f'Write a BED file:\t{bed}') df_bed.to_csv(bed, sep='\t', header=False, index=False) def _identify_target_region(chrom, sequence, target_letter_set): bseq = pd.Series(list(sequence)).isin(target_letter_set).astype(int) if bseq.sum() > 0: return bseq.pipe( lambda s: pd.DataFrame({ 'chrom': chrom, 'chromStart': [ *([0] if s.iloc[0] == 1 else list()), *s[s.diff() == 1].index ], 'chromEnd': [ *s[s.diff() == -1].index, *([len(s)] if s.iloc[-1] == 1 else list()) ] }) ) else: logger = logging.getLogger(__name__) logger.info(f'Target letters not detected: {chrom}')
0.284377
0.263368
import logging import os import re import subprocess import sys import time from webkitpy.benchmark_runner.http_server_driver.http_server_driver import HTTPServerDriver _log = logging.getLogger(__name__) class SimpleHTTPServerDriver(HTTPServerDriver): """This class depends on unix environment, need to be modified to achieve crossplatform compability """ platforms = ['osx', 'linux'] def __init__(self): self._server_process = None self._server_port = 0 self._ip = '127.0.0.1' self._ensure_http_server_dependencies() def serve(self, web_root): _log.info('Launching an http server') http_server_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "http_server/twisted_http_server.py") interface_args = [] if self._ip: interface_args.extend(['--interface', self._ip]) self._server_process = subprocess.Popen(["python", http_server_path, web_root] + interface_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) max_attempt = 5 interval = 0.5 _log.info('Start to fetching the port number of the http server') try: import psutil for attempt in range(max_attempt): connections = psutil.Process(self._server_process.pid).connections() if connections and connections[0].laddr and connections[0].laddr[1] and connections[0].status == 'LISTEN': self._server_port = connections[0].laddr[1] _log.info('HTTP Server is serving at port: %d', self._server_port) break _log.info('Server port is not found this time, retry after %f seconds' % interval) time.sleep(interval) interval *= 2 else: raise Exception("Server is not listening on port, max tries exceeded. HTTP server may be installing dependent modules.") except ImportError: for attempt in range(max_attempt): try: output = subprocess.check_output(['/usr/sbin/lsof', '-a', '-P', '-iTCP', '-sTCP:LISTEN', '-p', str(self._server_process.pid)]) self._server_port = int(re.search('TCP .*:(\d+) \(LISTEN\)', output).group(1)) if self._server_port: _log.info('HTTP Server is serving at port: %d', self._server_port) break except Exception as error: _log.info('Error: %s' % error) _log.info('Server port is not found this time, retry after %f seconds' % interval) time.sleep(interval) interval *= 2 else: raise Exception("Cannot listen to server, max tries exceeded") self._wait_for_http_server() def _wait_for_http_server(self): max_attempt = 5 # Wait for server to be up completely before exiting for attempt in range(max_attempt): try: subprocess.check_call(["curl", "--silent", "--head", "--fail", "--output", "/dev/null", self.base_url()]) return except Exception as error: _log.info('Server not running yet: %s' % error) time.sleep(1) raise Exception('Server not running, max tries exceeded: %s' % error) def base_url(self): return "http://%s:%d" % (self._ip, self._server_port) def fetch_result(self): (stdout, stderr) = self._server_process.communicate() print(stderr) return stdout def kill_server(self): try: if not self._server_process: return if self._server_process.poll() is None: self._server_process.terminate() except OSError as error: _log.info('Error terminating server process: %s' % (error)) def get_return_code(self): return self._server_process.returncode def set_device_id(self, device_id): pass def _ensure_http_server_dependencies(self): _log.info('Ensure dependencies of http server is satisfied') from pkg_resources import require, VersionConflict, DistributionNotFound try: require("Twisted>=15.5.0") import twisted except (ImportError, VersionConflict, DistributionNotFound): _log.info("Will install twisted in webkitpy, and twisted will be used by webkitpy only") sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../..'))) from webkitpy.thirdparty.autoinstalled.twisted_15_5_0 import twisted
Tools/Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py
import logging import os import re import subprocess import sys import time from webkitpy.benchmark_runner.http_server_driver.http_server_driver import HTTPServerDriver _log = logging.getLogger(__name__) class SimpleHTTPServerDriver(HTTPServerDriver): """This class depends on unix environment, need to be modified to achieve crossplatform compability """ platforms = ['osx', 'linux'] def __init__(self): self._server_process = None self._server_port = 0 self._ip = '127.0.0.1' self._ensure_http_server_dependencies() def serve(self, web_root): _log.info('Launching an http server') http_server_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "http_server/twisted_http_server.py") interface_args = [] if self._ip: interface_args.extend(['--interface', self._ip]) self._server_process = subprocess.Popen(["python", http_server_path, web_root] + interface_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) max_attempt = 5 interval = 0.5 _log.info('Start to fetching the port number of the http server') try: import psutil for attempt in range(max_attempt): connections = psutil.Process(self._server_process.pid).connections() if connections and connections[0].laddr and connections[0].laddr[1] and connections[0].status == 'LISTEN': self._server_port = connections[0].laddr[1] _log.info('HTTP Server is serving at port: %d', self._server_port) break _log.info('Server port is not found this time, retry after %f seconds' % interval) time.sleep(interval) interval *= 2 else: raise Exception("Server is not listening on port, max tries exceeded. HTTP server may be installing dependent modules.") except ImportError: for attempt in range(max_attempt): try: output = subprocess.check_output(['/usr/sbin/lsof', '-a', '-P', '-iTCP', '-sTCP:LISTEN', '-p', str(self._server_process.pid)]) self._server_port = int(re.search('TCP .*:(\d+) \(LISTEN\)', output).group(1)) if self._server_port: _log.info('HTTP Server is serving at port: %d', self._server_port) break except Exception as error: _log.info('Error: %s' % error) _log.info('Server port is not found this time, retry after %f seconds' % interval) time.sleep(interval) interval *= 2 else: raise Exception("Cannot listen to server, max tries exceeded") self._wait_for_http_server() def _wait_for_http_server(self): max_attempt = 5 # Wait for server to be up completely before exiting for attempt in range(max_attempt): try: subprocess.check_call(["curl", "--silent", "--head", "--fail", "--output", "/dev/null", self.base_url()]) return except Exception as error: _log.info('Server not running yet: %s' % error) time.sleep(1) raise Exception('Server not running, max tries exceeded: %s' % error) def base_url(self): return "http://%s:%d" % (self._ip, self._server_port) def fetch_result(self): (stdout, stderr) = self._server_process.communicate() print(stderr) return stdout def kill_server(self): try: if not self._server_process: return if self._server_process.poll() is None: self._server_process.terminate() except OSError as error: _log.info('Error terminating server process: %s' % (error)) def get_return_code(self): return self._server_process.returncode def set_device_id(self, device_id): pass def _ensure_http_server_dependencies(self): _log.info('Ensure dependencies of http server is satisfied') from pkg_resources import require, VersionConflict, DistributionNotFound try: require("Twisted>=15.5.0") import twisted except (ImportError, VersionConflict, DistributionNotFound): _log.info("Will install twisted in webkitpy, and twisted will be used by webkitpy only") sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../..'))) from webkitpy.thirdparty.autoinstalled.twisted_15_5_0 import twisted
0.257578
0.04904
import pickle import sqlite3 import logging from collections import namedtuple from sanskrit_parser.base.sanskrit_base import SanskritImmutableString, SCHEMES from sanskrit_parser.util.lexical_lookup import LexicalLookup from sanskrit_parser.util.inriatagmapper import inriaTagMapper from sanskrit_parser.util.data_manager import data_file_path _db = namedtuple('_db', ['db_file', 'tags', 'stems', 'buf']) class InriaXMLWrapper(LexicalLookup): """ Class to interface with the INRIA XML database released by Prof. <NAME> https://gitlab.inria.fr/huet/Heritage_Resources """ ''' The custom database format has two parts: 1. A pickle file that contains a list of stems, a list of tags, and a serialized buffer of the indices of stems and tags for each form. The indices are used as it is more efficient to store such integers instead of the string for each tag. 2. An sqlite file that maps each form to the position within the buffer that contains the serialized tuple of stems and tags for that form. An sqlite database is used to avoid having to build a huge dict in memory for the 600K forms that are present in this db, which consumes a lot of memory. (See https://github.com/kmadathil/sanskrit_parser/issues/151) To lookup the tag for a form, we use the sqlite db to find the position in the buffer, deserialize the data at that position, which gives us a list of the tag set for that form. For each item in that list, we then lookup the right stem and tag in the list of stems and tags loaded from the pickle file ''' def __init__(self, logger=None): self.pickle_file = "inria_forms.pickle" self.logger = logger or logging.getLogger(__name__) db_file = data_file_path("inria_forms_pos.db") pkl_path = data_file_path("inria_stems_tags_buf.pkl") self.db = self._load_db(db_file, pkl_path) @staticmethod def _load_db(db_file, pkl_path): with open(pkl_path, 'rb') as f: stems = pickle.load(f) tags = pickle.load(f) buf = f.read() db = _db(db_file, tags, stems, buf) return db def _get_tags(self, word): db = self.db conn = sqlite3.connect(db.db_file) cursor = conn.cursor() res = cursor.execute('SELECT * FROM forms WHERE form=?', (word,)).fetchone() if res is None: return None pos = res[1] tag_index_list = pickle.loads(db.buf[pos:]) tags = [] for tag_index in tag_index_list: tags.append(self._decode_tags(tag_index, db.tags, db.stems)) return tags @staticmethod def _decode_tags(tag_index, tags, stems): t = [tags[x] for x in tag_index[1]] stem = stems[tag_index[0]] return (stem, set(t)) def valid(self, word): conn = sqlite3.connect(self.db.db_file) cursor = conn.cursor() res = cursor.execute('SELECT COUNT(1) FROM forms WHERE form = ?', (word,)).fetchone() return res[0] > 0 def get_tags(self, word, tmap=True): tags = self._get_tags(word) if tmap and (tags is not None): tags = inriaTagMapper(tags) return tags if __name__ == "__main__": from argparse import ArgumentParser def getArgs(): """ Argparse routine. Returns args variable """ # Parser Setup parser = ArgumentParser(description='Interface to INRIA XML database') # Input Encoding (autodetect by default) parser.add_argument('--input-encoding', type=str, default=None) parser.add_argument('--loglevel', type=str, default="info", help="logging level. Can be any level supported by logging module") parser.add_argument('word', nargs='?', type=str, default=None, help="Word to look up") parser.add_argument('--no-map-tags', dest='map_tags', action='store_false') return parser.parse_args() def main(): args = getArgs() if args.input_encoding is None: ie = None else: ie = SCHEMES[args.input_encoding] if args.loglevel: numeric_level = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % args.loglevel) logging.basicConfig(level=numeric_level) word_in = SanskritImmutableString(args.word, encoding=ie).canonical() xmlDB = InriaXMLWrapper() print("Getting tags for", word_in) tags = xmlDB.get_tags(word_in, tmap=args.map_tags) if tags is not None: for t in tags: print(t) main()
sanskrit_parser/util/inriaxmlwrapper.py
import pickle import sqlite3 import logging from collections import namedtuple from sanskrit_parser.base.sanskrit_base import SanskritImmutableString, SCHEMES from sanskrit_parser.util.lexical_lookup import LexicalLookup from sanskrit_parser.util.inriatagmapper import inriaTagMapper from sanskrit_parser.util.data_manager import data_file_path _db = namedtuple('_db', ['db_file', 'tags', 'stems', 'buf']) class InriaXMLWrapper(LexicalLookup): """ Class to interface with the INRIA XML database released by Prof. <NAME> https://gitlab.inria.fr/huet/Heritage_Resources """ ''' The custom database format has two parts: 1. A pickle file that contains a list of stems, a list of tags, and a serialized buffer of the indices of stems and tags for each form. The indices are used as it is more efficient to store such integers instead of the string for each tag. 2. An sqlite file that maps each form to the position within the buffer that contains the serialized tuple of stems and tags for that form. An sqlite database is used to avoid having to build a huge dict in memory for the 600K forms that are present in this db, which consumes a lot of memory. (See https://github.com/kmadathil/sanskrit_parser/issues/151) To lookup the tag for a form, we use the sqlite db to find the position in the buffer, deserialize the data at that position, which gives us a list of the tag set for that form. For each item in that list, we then lookup the right stem and tag in the list of stems and tags loaded from the pickle file ''' def __init__(self, logger=None): self.pickle_file = "inria_forms.pickle" self.logger = logger or logging.getLogger(__name__) db_file = data_file_path("inria_forms_pos.db") pkl_path = data_file_path("inria_stems_tags_buf.pkl") self.db = self._load_db(db_file, pkl_path) @staticmethod def _load_db(db_file, pkl_path): with open(pkl_path, 'rb') as f: stems = pickle.load(f) tags = pickle.load(f) buf = f.read() db = _db(db_file, tags, stems, buf) return db def _get_tags(self, word): db = self.db conn = sqlite3.connect(db.db_file) cursor = conn.cursor() res = cursor.execute('SELECT * FROM forms WHERE form=?', (word,)).fetchone() if res is None: return None pos = res[1] tag_index_list = pickle.loads(db.buf[pos:]) tags = [] for tag_index in tag_index_list: tags.append(self._decode_tags(tag_index, db.tags, db.stems)) return tags @staticmethod def _decode_tags(tag_index, tags, stems): t = [tags[x] for x in tag_index[1]] stem = stems[tag_index[0]] return (stem, set(t)) def valid(self, word): conn = sqlite3.connect(self.db.db_file) cursor = conn.cursor() res = cursor.execute('SELECT COUNT(1) FROM forms WHERE form = ?', (word,)).fetchone() return res[0] > 0 def get_tags(self, word, tmap=True): tags = self._get_tags(word) if tmap and (tags is not None): tags = inriaTagMapper(tags) return tags if __name__ == "__main__": from argparse import ArgumentParser def getArgs(): """ Argparse routine. Returns args variable """ # Parser Setup parser = ArgumentParser(description='Interface to INRIA XML database') # Input Encoding (autodetect by default) parser.add_argument('--input-encoding', type=str, default=None) parser.add_argument('--loglevel', type=str, default="info", help="logging level. Can be any level supported by logging module") parser.add_argument('word', nargs='?', type=str, default=None, help="Word to look up") parser.add_argument('--no-map-tags', dest='map_tags', action='store_false') return parser.parse_args() def main(): args = getArgs() if args.input_encoding is None: ie = None else: ie = SCHEMES[args.input_encoding] if args.loglevel: numeric_level = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % args.loglevel) logging.basicConfig(level=numeric_level) word_in = SanskritImmutableString(args.word, encoding=ie).canonical() xmlDB = InriaXMLWrapper() print("Getting tags for", word_in) tags = xmlDB.get_tags(word_in, tmap=args.map_tags) if tags is not None: for t in tags: print(t) main()
0.552781
0.339171
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.label import Label class MainApp(App): def build(self): self.operators = ["/", "*", "+","%","^","Mod"] self.last_was_operator = None self.last_button = None main_layout = BoxLayout(orientation="vertical") #label main_layout.add_widget(Label(text="Calvy - Kivy Calculator", size_hint = (.4, .4), pos_hint={"center_x": 0.5, "center_y": 0.5})) #display self.calculation = TextInput( multiline=True, readonly=True, halign="right", font_size=250) self.output = TextInput( multiline=False, readonly=True, halign="right", font_size=250) main_layout.add_widget(self.calculation) main_layout.add_widget(self.output) buttons = [ ["Mod","(",")","Ans"], ["^", "%","Del","+"], ["7", "8", "9", "-"], ["4", "5", "6", "*"], ["1", "2", "3", "/"], [".", "0", "C", "="], ] for row in buttons: h_layout = BoxLayout() for label in row: if label == "=": button = Button( text=label, background_color = (0, 1, 1, 1), pos_hint={"center_x": 0.5, "center_y": 0.5}) button.bind(on_press=self.calculate) h_layout.add_widget(button) continue button = Button( text=label, pos_hint={"center_x": 0.4, "center_y": 0.4}) button.bind(on_press=self.on_button_press) h_layout.add_widget(button) main_layout.add_widget(h_layout) return main_layout def on_button_press(self, instance): current = self.calculation.text button_text = instance.text if button_text == "C": # Clear the calculation widget self.calculation.text = "" elif button_text == "Del": self.calculation.text = self.calculation.text[:-1] elif button_text == "Ans": self.calculation.text += self.output.text else: if current and ( self.last_was_operator and button_text in self.operators): # Don't add two operators right after each other return elif current == "" and ( button_text in self.operators or button_text == "0"): # First character cannot be an operator or zero return else: new_text = current + button_text self.calculation.text = new_text self.last_button = button_text self.last_was_operator = self.last_button in self.operators def calculate(self, instance): text = self.calculation.text if text: try: #replacing operators to python operators y = text.replace("^", "**") x = y.replace("%","*(0.01)*") self.output.text = x.replace("Mod","%") calculation = str(eval(self.output.text)) self.output.text = calculation self.calculation.text = "" except Exception: self.output.text = "Error" self.calculation.text = "" if __name__ == "__main__": app = MainApp() app.run()
Calvy/main.py
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.label import Label class MainApp(App): def build(self): self.operators = ["/", "*", "+","%","^","Mod"] self.last_was_operator = None self.last_button = None main_layout = BoxLayout(orientation="vertical") #label main_layout.add_widget(Label(text="Calvy - Kivy Calculator", size_hint = (.4, .4), pos_hint={"center_x": 0.5, "center_y": 0.5})) #display self.calculation = TextInput( multiline=True, readonly=True, halign="right", font_size=250) self.output = TextInput( multiline=False, readonly=True, halign="right", font_size=250) main_layout.add_widget(self.calculation) main_layout.add_widget(self.output) buttons = [ ["Mod","(",")","Ans"], ["^", "%","Del","+"], ["7", "8", "9", "-"], ["4", "5", "6", "*"], ["1", "2", "3", "/"], [".", "0", "C", "="], ] for row in buttons: h_layout = BoxLayout() for label in row: if label == "=": button = Button( text=label, background_color = (0, 1, 1, 1), pos_hint={"center_x": 0.5, "center_y": 0.5}) button.bind(on_press=self.calculate) h_layout.add_widget(button) continue button = Button( text=label, pos_hint={"center_x": 0.4, "center_y": 0.4}) button.bind(on_press=self.on_button_press) h_layout.add_widget(button) main_layout.add_widget(h_layout) return main_layout def on_button_press(self, instance): current = self.calculation.text button_text = instance.text if button_text == "C": # Clear the calculation widget self.calculation.text = "" elif button_text == "Del": self.calculation.text = self.calculation.text[:-1] elif button_text == "Ans": self.calculation.text += self.output.text else: if current and ( self.last_was_operator and button_text in self.operators): # Don't add two operators right after each other return elif current == "" and ( button_text in self.operators or button_text == "0"): # First character cannot be an operator or zero return else: new_text = current + button_text self.calculation.text = new_text self.last_button = button_text self.last_was_operator = self.last_button in self.operators def calculate(self, instance): text = self.calculation.text if text: try: #replacing operators to python operators y = text.replace("^", "**") x = y.replace("%","*(0.01)*") self.output.text = x.replace("Mod","%") calculation = str(eval(self.output.text)) self.output.text = calculation self.calculation.text = "" except Exception: self.output.text = "Error" self.calculation.text = "" if __name__ == "__main__": app = MainApp() app.run()
0.421552
0.204878
import os import sys import requests import time from datetime import date, datetime, timedelta import json import pickle import logging from collections import deque from configparser import ConfigParser from optparse import OptionParser from ifobfuscate import decode import warnings warnings.filterwarnings('ignore') class GeneratePredictedIncidentServiceNowTicket: ''' Get predicted incident data from InsightFinder and send to ServiceNow ''' def __init__(self): if os.path.exists(config_path): self.get_config_vars() else: message = "No config file found. Exiting." print(message) logger.error(message) sys.exit(1) self.incident_record = incident_record def get_config_vars(self): ''' Get config variables from the config file ''' config = ConfigParser() config.read(config_path) self.insightFinder_vars = {} self.insightFinder_vars['host_url'] = config.get('insightFinder_vars', 'host_url') self.insightFinder_vars['http_proxy'] = config.get('insightFinder_vars', 'http_proxy') self.insightFinder_vars['https_proxy'] = config.get('insightFinder_vars', 'https_proxy') self.insightFinder_vars['licenseKey'] = config.get('insightFinder_vars', 'licenseKey') self.insightFinder_vars['retries'] = config.getint('insightFinder_vars', 'retries') self.insightFinder_vars['sleep_seconds'] = config.getint('insightFinder_vars', 'sleep_seconds') self.serviceNow_vars = {} self.serviceNow_vars['host_url'] = config.get('serviceNow_vars', 'host_url') self.serviceNow_vars['http_proxy'] = config.get('serviceNow_vars', 'http_proxy') self.serviceNow_vars['https_proxy'] = config.get('serviceNow_vars', 'https_proxy') self.serviceNow_vars['api'] = config.get('serviceNow_vars', 'api') self.serviceNow_vars['username'] = config.get('serviceNow_vars', 'username') self.serviceNow_vars['password'] = decode(config.get('serviceNow_vars', 'password')) self.serviceNow_vars['target_table'] = config.get('serviceNow_vars', 'target_table') self.serviceNow_vars['retries'] = config.getint('serviceNow_vars', 'retries') self.serviceNow_vars['sleep_seconds'] = config.getint('serviceNow_vars', 'sleep_seconds') self.serviceNow_vars['dampening_minutes'] = config.getint('serviceNow_vars', 'dampening_minutes') self.payload_vars = {} self.payload_vars['environment_name'] = config.get('payload_vars', 'environment_name') self.payload_vars['system_id_list'] = config.get('payload_vars', 'system_id_list').split(',') self.payload_vars['system_id_list'] = str([{'id': id.strip()} for id in self.payload_vars['system_id_list']]) self.payload_vars['customer_name'] = config.get('payload_vars', 'customer_name') self.payload_vars['start_date'] = config.get('payload_vars', 'start_date') self.payload_vars['end_date'] = config.get('payload_vars', 'end_date') parser = OptionParser() parser.add_option('-t', '--testing', action='store_true', dest='testing', default=False, help='Set to testing mode (do not send data).') (self.options, args) = parser.parse_args() def post_all_incidents(self): ''' Process all incidents between the start and end dates If either date variable is a null value, it is set to today's datetime ''' time_now = datetime.now() start_date = datetime.fromisoformat(self.payload_vars['start_date']) if self.payload_vars['start_date'] else time_now end_date = datetime.fromisoformat(self.payload_vars['end_date']) if self.payload_vars['end_date'] else time_now if start_date > end_date: message = "WARNING: Start Date ({}) > End Date ({}). No incidents would be transferred.".format( start_date, end_date) print(message) logger.info(message) day = start_date while day <= end_date: data = self.get_predicted_incident_json(day) if not self.options.testing: self.post_day_incidents(data) day += timedelta(days=1) def get_predicted_incident_json(self, day): ''' Get predicted incident data for EXACTLY a day from InsightFinder in JSON format RETURNS: dict/JSON ''' url = self.insightFinder_vars['host_url'] + "/api/v2/servicenowagentpush" proxies = {} if len(self.insightFinder_vars['http_proxy']) > 0: proxies['http'] = self.insightFinder_vars['http_proxy'] if len(self.insightFinder_vars['https_proxy']) > 0: proxies['https'] = self.insightFinder_vars['https_proxy'] data = { 'environmentName': self.payload_vars['environment_name'], 'systemIds': self.payload_vars['system_id_list'], 'customerName': self.payload_vars['customer_name'], 'licenseKey': self.insightFinder_vars['licenseKey'], 'targetTable': self.serviceNow_vars['target_table'], 'startTime': int(time.mktime(day.astimezone().timetuple())) * 1000 } attempts = 1 response = requests.get(url, params=data, proxies=proxies, verify=False) while response.status_code != 200 and attempts < self.insightFinder_vars['retries']: print("Failed to get data for {}. Retrying in {} seconds.".format( day, self.insightFinder_vars['sleep_seconds'])) time.sleep(self.insightFinder_vars['sleep_seconds']) response = requests.get(url, params=data, proxies=proxies, verify=False) attempts += 1 if response.status_code == 200: data = response.json() message = "\nSuccessfully retrieved {} incidents for {} from InsightFinder.".format(len(data), day) print(message) logger.info(message) return data else: message = "Failed to get data for {} in {} attempts. Check logs for details.".format( day, self.insightFinder_vars['retries']) print(message) logger.warning("{} Status Code: {}. Response Text: {}. Response URL: {}.".format( message, response.status_code, response.text, response.url)) return {} def post_day_incidents(self, day_data): ''' Process all incidents in a day's worth of incident data EXCEPT those re-observed in 'dampening_minutes' interval ''' total_incidents = len(day_data) queued = 0 dampened = 0 for incident_data in day_data: print("Total incidents: {} ; Queued for ServiceNow : {} ; Dampened : {}".format( total_incidents, queued, dampened), end='\r') incident_key = incident_data['incidentId'] incident_last_observed = self.incident_record.get(incident_key, None) if incident_last_observed and ((incident_data['startTime'] - incident_last_observed) / (1000*60) < self.serviceNow_vars['dampening_minutes']): dampened += 1 continue payload = self.create_serviceNow_payload(incident_data) payload_queue.append(payload) self.incident_record[incident_key] = incident_data['startTime'] queued += 1 message = "Total incidents: {} ; Queued for ServiceNow : {} ; Dampened : {}".format( total_incidents, queued, dampened) print(message) logger.info(message) queue_len = len(payload_queue) while payload_queue: if self.post_serviceNow_ticket(payload_queue[0]): payload_queue.popleft() print("Total incidents in the queue: {} ; Successfully sent: {}".format( queue_len, queue_len - len(payload_queue)), end='\r') else: break message = "Total incidents in the queue: {} ; Successfully sent: {}".format( queue_len, queue_len - len(payload_queue)) print(message) logger.info(message) def create_serviceNow_payload(self, incident_data): ''' Create single incident data paylaod to send to ServiceNow RETURNS: str/JSON ''' payload = incident_data.copy() del payload['incidentId'], payload['startTime'] payload = json.dumps(payload) return payload def post_serviceNow_ticket(self, payload): ''' Send a single incident ticket to ServiceNow RETURNS: Boolean // whether the ticket was posted successfully ''' url = self.serviceNow_vars['host_url'] + self.serviceNow_vars['api'] headers = {"Content-Type": "application/json", "Accept": "application/json"} proxies = {} if len(self.serviceNow_vars['http_proxy']) > 0: proxies['http'] = self.serviceNow_vars['http_proxy'] if len(self.serviceNow_vars['https_proxy']) > 0: proxies['https'] = self.serviceNow_vars['https_proxy'] attempts = 1 response = requests.post(url, auth=(self.serviceNow_vars['username'], self.serviceNow_vars['password']), headers=headers, data=payload, proxies=proxies, verify=False) while response.status_code != 201 and attempts < self.serviceNow_vars['retries']: print("Failed to post data to ServiceNow. Retrying in {} seconds.".format( self.serviceNow_vars['sleep_seconds'])) time.sleep(self.serviceNow_vars['sleep_seconds']) response = requests.post(url, auth=(self.serviceNow_vars['username'], self.serviceNow_vars['password']), headers=headers, data=payload, proxies=proxies, verify=False) attempts += 1 if response.status_code != 201: message = "Failed to post data to ServiceNow in {} attempts. Check logs for details.".format( self.serviceNow_vars['retries']) print(message) logger.warning("Status Code: {}. Response Text: {}. Response URL: {}.".format( response.status_code, response.text, response.url)) return response.status_code == 201 if __name__ == '__main__': config_path = 'config.ini' incident_record_path = 'incident_record.pkl' payload_queue_path = 'payload_queue.pkl' log_record_path = 'log_record.log' ''' The incident_record pickle stores the past post requests made as a dictionary object ** ('projectName', 'componentName', 'patternId') -> latest_timeStamp_of_corresponding_post_request ** No same incident (defined by the key) will be posted before or within the 'dampening_minutes' interval of last such request Delete the pickle file to reset the record (may especially be required for processing historical data) ''' if os.path.exists(incident_record_path): with open(incident_record_path, 'rb') as handle: incident_record = pickle.load(handle) else: incident_record = {} if os.path.exists(payload_queue_path): with open(payload_queue_path, 'rb') as handle: payload_queue = pickle.load(handle) else: payload_queue = deque() logging.basicConfig(filename = log_record_path, format = ('%(asctime)s %(filename)s: %(levelname)s: %(funcName)s(): %(lineno)d:\t %(message)s')) logger = logging.getLogger() logger.setLevel(logging.INFO) try: generator = GeneratePredictedIncidentServiceNowTicket() generator.post_all_incidents() except Exception as e: print("ERROR. Check logs.") logger.error(e, exc_info=True) with open(incident_record_path, 'wb') as handle: pickle.dump(incident_record, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(payload_queue_path, 'wb') as handle: pickle.dump(payload_queue, handle, protocol=pickle.HIGHEST_PROTOCOL)
insightFinderToServiceNow/GeneratePredictedIncidentServiceNowTicket.py
import os import sys import requests import time from datetime import date, datetime, timedelta import json import pickle import logging from collections import deque from configparser import ConfigParser from optparse import OptionParser from ifobfuscate import decode import warnings warnings.filterwarnings('ignore') class GeneratePredictedIncidentServiceNowTicket: ''' Get predicted incident data from InsightFinder and send to ServiceNow ''' def __init__(self): if os.path.exists(config_path): self.get_config_vars() else: message = "No config file found. Exiting." print(message) logger.error(message) sys.exit(1) self.incident_record = incident_record def get_config_vars(self): ''' Get config variables from the config file ''' config = ConfigParser() config.read(config_path) self.insightFinder_vars = {} self.insightFinder_vars['host_url'] = config.get('insightFinder_vars', 'host_url') self.insightFinder_vars['http_proxy'] = config.get('insightFinder_vars', 'http_proxy') self.insightFinder_vars['https_proxy'] = config.get('insightFinder_vars', 'https_proxy') self.insightFinder_vars['licenseKey'] = config.get('insightFinder_vars', 'licenseKey') self.insightFinder_vars['retries'] = config.getint('insightFinder_vars', 'retries') self.insightFinder_vars['sleep_seconds'] = config.getint('insightFinder_vars', 'sleep_seconds') self.serviceNow_vars = {} self.serviceNow_vars['host_url'] = config.get('serviceNow_vars', 'host_url') self.serviceNow_vars['http_proxy'] = config.get('serviceNow_vars', 'http_proxy') self.serviceNow_vars['https_proxy'] = config.get('serviceNow_vars', 'https_proxy') self.serviceNow_vars['api'] = config.get('serviceNow_vars', 'api') self.serviceNow_vars['username'] = config.get('serviceNow_vars', 'username') self.serviceNow_vars['password'] = decode(config.get('serviceNow_vars', 'password')) self.serviceNow_vars['target_table'] = config.get('serviceNow_vars', 'target_table') self.serviceNow_vars['retries'] = config.getint('serviceNow_vars', 'retries') self.serviceNow_vars['sleep_seconds'] = config.getint('serviceNow_vars', 'sleep_seconds') self.serviceNow_vars['dampening_minutes'] = config.getint('serviceNow_vars', 'dampening_minutes') self.payload_vars = {} self.payload_vars['environment_name'] = config.get('payload_vars', 'environment_name') self.payload_vars['system_id_list'] = config.get('payload_vars', 'system_id_list').split(',') self.payload_vars['system_id_list'] = str([{'id': id.strip()} for id in self.payload_vars['system_id_list']]) self.payload_vars['customer_name'] = config.get('payload_vars', 'customer_name') self.payload_vars['start_date'] = config.get('payload_vars', 'start_date') self.payload_vars['end_date'] = config.get('payload_vars', 'end_date') parser = OptionParser() parser.add_option('-t', '--testing', action='store_true', dest='testing', default=False, help='Set to testing mode (do not send data).') (self.options, args) = parser.parse_args() def post_all_incidents(self): ''' Process all incidents between the start and end dates If either date variable is a null value, it is set to today's datetime ''' time_now = datetime.now() start_date = datetime.fromisoformat(self.payload_vars['start_date']) if self.payload_vars['start_date'] else time_now end_date = datetime.fromisoformat(self.payload_vars['end_date']) if self.payload_vars['end_date'] else time_now if start_date > end_date: message = "WARNING: Start Date ({}) > End Date ({}). No incidents would be transferred.".format( start_date, end_date) print(message) logger.info(message) day = start_date while day <= end_date: data = self.get_predicted_incident_json(day) if not self.options.testing: self.post_day_incidents(data) day += timedelta(days=1) def get_predicted_incident_json(self, day): ''' Get predicted incident data for EXACTLY a day from InsightFinder in JSON format RETURNS: dict/JSON ''' url = self.insightFinder_vars['host_url'] + "/api/v2/servicenowagentpush" proxies = {} if len(self.insightFinder_vars['http_proxy']) > 0: proxies['http'] = self.insightFinder_vars['http_proxy'] if len(self.insightFinder_vars['https_proxy']) > 0: proxies['https'] = self.insightFinder_vars['https_proxy'] data = { 'environmentName': self.payload_vars['environment_name'], 'systemIds': self.payload_vars['system_id_list'], 'customerName': self.payload_vars['customer_name'], 'licenseKey': self.insightFinder_vars['licenseKey'], 'targetTable': self.serviceNow_vars['target_table'], 'startTime': int(time.mktime(day.astimezone().timetuple())) * 1000 } attempts = 1 response = requests.get(url, params=data, proxies=proxies, verify=False) while response.status_code != 200 and attempts < self.insightFinder_vars['retries']: print("Failed to get data for {}. Retrying in {} seconds.".format( day, self.insightFinder_vars['sleep_seconds'])) time.sleep(self.insightFinder_vars['sleep_seconds']) response = requests.get(url, params=data, proxies=proxies, verify=False) attempts += 1 if response.status_code == 200: data = response.json() message = "\nSuccessfully retrieved {} incidents for {} from InsightFinder.".format(len(data), day) print(message) logger.info(message) return data else: message = "Failed to get data for {} in {} attempts. Check logs for details.".format( day, self.insightFinder_vars['retries']) print(message) logger.warning("{} Status Code: {}. Response Text: {}. Response URL: {}.".format( message, response.status_code, response.text, response.url)) return {} def post_day_incidents(self, day_data): ''' Process all incidents in a day's worth of incident data EXCEPT those re-observed in 'dampening_minutes' interval ''' total_incidents = len(day_data) queued = 0 dampened = 0 for incident_data in day_data: print("Total incidents: {} ; Queued for ServiceNow : {} ; Dampened : {}".format( total_incidents, queued, dampened), end='\r') incident_key = incident_data['incidentId'] incident_last_observed = self.incident_record.get(incident_key, None) if incident_last_observed and ((incident_data['startTime'] - incident_last_observed) / (1000*60) < self.serviceNow_vars['dampening_minutes']): dampened += 1 continue payload = self.create_serviceNow_payload(incident_data) payload_queue.append(payload) self.incident_record[incident_key] = incident_data['startTime'] queued += 1 message = "Total incidents: {} ; Queued for ServiceNow : {} ; Dampened : {}".format( total_incidents, queued, dampened) print(message) logger.info(message) queue_len = len(payload_queue) while payload_queue: if self.post_serviceNow_ticket(payload_queue[0]): payload_queue.popleft() print("Total incidents in the queue: {} ; Successfully sent: {}".format( queue_len, queue_len - len(payload_queue)), end='\r') else: break message = "Total incidents in the queue: {} ; Successfully sent: {}".format( queue_len, queue_len - len(payload_queue)) print(message) logger.info(message) def create_serviceNow_payload(self, incident_data): ''' Create single incident data paylaod to send to ServiceNow RETURNS: str/JSON ''' payload = incident_data.copy() del payload['incidentId'], payload['startTime'] payload = json.dumps(payload) return payload def post_serviceNow_ticket(self, payload): ''' Send a single incident ticket to ServiceNow RETURNS: Boolean // whether the ticket was posted successfully ''' url = self.serviceNow_vars['host_url'] + self.serviceNow_vars['api'] headers = {"Content-Type": "application/json", "Accept": "application/json"} proxies = {} if len(self.serviceNow_vars['http_proxy']) > 0: proxies['http'] = self.serviceNow_vars['http_proxy'] if len(self.serviceNow_vars['https_proxy']) > 0: proxies['https'] = self.serviceNow_vars['https_proxy'] attempts = 1 response = requests.post(url, auth=(self.serviceNow_vars['username'], self.serviceNow_vars['password']), headers=headers, data=payload, proxies=proxies, verify=False) while response.status_code != 201 and attempts < self.serviceNow_vars['retries']: print("Failed to post data to ServiceNow. Retrying in {} seconds.".format( self.serviceNow_vars['sleep_seconds'])) time.sleep(self.serviceNow_vars['sleep_seconds']) response = requests.post(url, auth=(self.serviceNow_vars['username'], self.serviceNow_vars['password']), headers=headers, data=payload, proxies=proxies, verify=False) attempts += 1 if response.status_code != 201: message = "Failed to post data to ServiceNow in {} attempts. Check logs for details.".format( self.serviceNow_vars['retries']) print(message) logger.warning("Status Code: {}. Response Text: {}. Response URL: {}.".format( response.status_code, response.text, response.url)) return response.status_code == 201 if __name__ == '__main__': config_path = 'config.ini' incident_record_path = 'incident_record.pkl' payload_queue_path = 'payload_queue.pkl' log_record_path = 'log_record.log' ''' The incident_record pickle stores the past post requests made as a dictionary object ** ('projectName', 'componentName', 'patternId') -> latest_timeStamp_of_corresponding_post_request ** No same incident (defined by the key) will be posted before or within the 'dampening_minutes' interval of last such request Delete the pickle file to reset the record (may especially be required for processing historical data) ''' if os.path.exists(incident_record_path): with open(incident_record_path, 'rb') as handle: incident_record = pickle.load(handle) else: incident_record = {} if os.path.exists(payload_queue_path): with open(payload_queue_path, 'rb') as handle: payload_queue = pickle.load(handle) else: payload_queue = deque() logging.basicConfig(filename = log_record_path, format = ('%(asctime)s %(filename)s: %(levelname)s: %(funcName)s(): %(lineno)d:\t %(message)s')) logger = logging.getLogger() logger.setLevel(logging.INFO) try: generator = GeneratePredictedIncidentServiceNowTicket() generator.post_all_incidents() except Exception as e: print("ERROR. Check logs.") logger.error(e, exc_info=True) with open(incident_record_path, 'wb') as handle: pickle.dump(incident_record, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(payload_queue_path, 'wb') as handle: pickle.dump(payload_queue, handle, protocol=pickle.HIGHEST_PROTOCOL)
0.305594
0.070528
from app.database.models import SalesVolumes from app.database import db from app.log import logger def create_new_record(record): with db.auto_commit_db(): new_sales = SalesVolumes(pid=record['pid'], sid=record['sid'], pname=record['pname'], date=record['date'], sales=record['sales']) db.session.add(new_sales) db.session.flush() rid = new_sales.id return rid def get_record_one_day(pid, date): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() return record def get_shop_records_one_day(sid, date): records = SalesVolumes.query.filter_by(sid=sid, date=date).all() return records def get_shop_records_by_period(sid, start, end): records = SalesVolumes.query.filter_by(sid=sid) \ .filter((SalesVolumes.date <= end) & (SalesVolumes.date >= start)) \ .order_by(SalesVolumes.date).all() return records def get_records_by_period(pid, start, end): records = SalesVolumes.query.filter_by(pid=pid) \ .filter((SalesVolumes.date <= end) & (SalesVolumes.date >= start)) \ .order_by(SalesVolumes.date).all() return records def update_record_sales(pid, date, sales): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() if record is not None: record.sales = sales db.session.commit() return True else: return False def delete_record(pid, date): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() if record is not None: db.session.delete(record) db.session.commit() logger.info(f'delete record (pid:{pid}, date:{date}) succeed') return True else: logger.info(f'delete record (pid:{pid}, date:{date}) failed, record not exists') return False def delete_records_by_date(date): SalesVolumes.query.filter_by(date=date).delete() db.session.commit() logger.info(f'delete records (date:{date}) succeed') return True def delete_records_by_pid(pid): SalesVolumes.query.filter_by(pid=pid).delete() db.session.commit() logger.info(f'delete records (pid:{pid}) succeed') return True def delete_records_by_sid(sid): SalesVolumes.query.filter_by(sid=sid).delete() db.session.commit() logger.info(f'delete records (sid:{sid}) succeed') return True
SA-be/app/database/salesVolumes.py
from app.database.models import SalesVolumes from app.database import db from app.log import logger def create_new_record(record): with db.auto_commit_db(): new_sales = SalesVolumes(pid=record['pid'], sid=record['sid'], pname=record['pname'], date=record['date'], sales=record['sales']) db.session.add(new_sales) db.session.flush() rid = new_sales.id return rid def get_record_one_day(pid, date): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() return record def get_shop_records_one_day(sid, date): records = SalesVolumes.query.filter_by(sid=sid, date=date).all() return records def get_shop_records_by_period(sid, start, end): records = SalesVolumes.query.filter_by(sid=sid) \ .filter((SalesVolumes.date <= end) & (SalesVolumes.date >= start)) \ .order_by(SalesVolumes.date).all() return records def get_records_by_period(pid, start, end): records = SalesVolumes.query.filter_by(pid=pid) \ .filter((SalesVolumes.date <= end) & (SalesVolumes.date >= start)) \ .order_by(SalesVolumes.date).all() return records def update_record_sales(pid, date, sales): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() if record is not None: record.sales = sales db.session.commit() return True else: return False def delete_record(pid, date): record = SalesVolumes.query.filter_by(pid=pid, date=date).first() if record is not None: db.session.delete(record) db.session.commit() logger.info(f'delete record (pid:{pid}, date:{date}) succeed') return True else: logger.info(f'delete record (pid:{pid}, date:{date}) failed, record not exists') return False def delete_records_by_date(date): SalesVolumes.query.filter_by(date=date).delete() db.session.commit() logger.info(f'delete records (date:{date}) succeed') return True def delete_records_by_pid(pid): SalesVolumes.query.filter_by(pid=pid).delete() db.session.commit() logger.info(f'delete records (pid:{pid}) succeed') return True def delete_records_by_sid(sid): SalesVolumes.query.filter_by(sid=sid).delete() db.session.commit() logger.info(f'delete records (sid:{sid}) succeed') return True
0.376165
0.125842
import logging import logging.config import os import torch import pickle import numpy as np logger=logging.getLogger(__name__) def init_logging(exp_dir, config_path='config/logging_config.yaml'): """ initial logging module with config :param config_path: :return: """ import yaml, sys try: with open(config_path, 'r') as f: config = yaml.load(f.read(), Loader=yaml.FullLoader) config["handlers"]["info_file_handler"]["filename"] = os.path.join(exp_dir, "info.log") config["handlers"]["time_file_handler"]["filename"] = os.path.join(exp_dir, "time.log") config["handlers"]["error_file_handler"]["filename"] = os.path.join(exp_dir, "error.log") logging.config.dictConfig(config) except IOError: sys.stderr.write('logging config file "%s" not found' % config_path) logging.basicConfig(level=logging.DEBUG) def get_hamming_dist(img_code, cap_code): if torch.cuda.is_available(): device='cuda' else: device='cpu' code_len = img_code.shape[1] similarity_matrix = [] for i in range(0, img_code.shape[0], 10): # 分片计算防止爆内存 cur_query_code = img_code[i:i + 10].to(device) # size(10,code_len) cur_matrix=[] for j in range(0,cap_code.shape[0],1000): cur_ref_code=cap_code[j:j+1000].to(device) cur_part=(code_len - (cur_query_code.unsqueeze(1) * cur_ref_code.unsqueeze(0)).sum(dim=-1)) / 2 # size(10,1000) cur_part=cur_part.cpu() cur_matrix.append(cur_part) cur_matrix = torch.cat(cur_matrix,dim=-1).cpu() similarity_matrix.append(cur_matrix) similarity_matrix = torch.cat(similarity_matrix, dim=0).cpu() return similarity_matrix def save_vector_to_file(data, file_name): pickle.dump(data, open(file_name, 'wb')) logger.info('save vector file to {}'.format(file_name)) def save_similarity_matrix(matrix_data,save_path): np.save(save_path,matrix_data) logger.info('save similarity matrix data into file: {}'.format(save_path))
utils.py
import logging import logging.config import os import torch import pickle import numpy as np logger=logging.getLogger(__name__) def init_logging(exp_dir, config_path='config/logging_config.yaml'): """ initial logging module with config :param config_path: :return: """ import yaml, sys try: with open(config_path, 'r') as f: config = yaml.load(f.read(), Loader=yaml.FullLoader) config["handlers"]["info_file_handler"]["filename"] = os.path.join(exp_dir, "info.log") config["handlers"]["time_file_handler"]["filename"] = os.path.join(exp_dir, "time.log") config["handlers"]["error_file_handler"]["filename"] = os.path.join(exp_dir, "error.log") logging.config.dictConfig(config) except IOError: sys.stderr.write('logging config file "%s" not found' % config_path) logging.basicConfig(level=logging.DEBUG) def get_hamming_dist(img_code, cap_code): if torch.cuda.is_available(): device='cuda' else: device='cpu' code_len = img_code.shape[1] similarity_matrix = [] for i in range(0, img_code.shape[0], 10): # 分片计算防止爆内存 cur_query_code = img_code[i:i + 10].to(device) # size(10,code_len) cur_matrix=[] for j in range(0,cap_code.shape[0],1000): cur_ref_code=cap_code[j:j+1000].to(device) cur_part=(code_len - (cur_query_code.unsqueeze(1) * cur_ref_code.unsqueeze(0)).sum(dim=-1)) / 2 # size(10,1000) cur_part=cur_part.cpu() cur_matrix.append(cur_part) cur_matrix = torch.cat(cur_matrix,dim=-1).cpu() similarity_matrix.append(cur_matrix) similarity_matrix = torch.cat(similarity_matrix, dim=0).cpu() return similarity_matrix def save_vector_to_file(data, file_name): pickle.dump(data, open(file_name, 'wb')) logger.info('save vector file to {}'.format(file_name)) def save_similarity_matrix(matrix_data,save_path): np.save(save_path,matrix_data) logger.info('save similarity matrix data into file: {}'.format(save_path))
0.252937
0.059674
import os import random import traceback import discord from discord.ext import commands, tasks GUILD = 384811165949231104 IMG_DIR = './data/server-icons' PLAN_Z = 507429352720433152 def find_file(i): images = os.listdir(IMG_DIR) for img_name in images: if img_name.startswith(str(i)): return f'{IMG_DIR}/{img_name}' return def shuffle_server_icons(): names = list(range(len(os.listdir(IMG_DIR)))) random.shuffle(names) for img_name in os.listdir(IMG_DIR): ext = img_name.split('.')[-1] os.rename(f'{IMG_DIR}/{img_name}', f'{IMG_DIR}/{names.pop()}.{ext}') class ServerIcon(commands.Cog): """Automatic server icon rotation.""" def __init__(self, bot): self.bot = bot # self.check_if_new_week.start() async def cog_command_error(self, ctx, error): if not isinstance(error, commands.CheckFailure): await ctx.send(f"```py\n{error.__class__.__name__}: {error}\n```") async def rotate_server_icon(self): try: guild = self.bot.get_guild(GUILD) img = random.choice(os.listdir(IMG_DIR)) img_path = f"{IMG_DIR}/{img}" with open(img_path, 'rb') as fp: icon = fp.read() await guild.edit(icon=icon) await self.log(f"Set server icon to `{img_path}`.") except Exception as e: error = ''.join(traceback.format_exception(e.__class__, e, e.__traceback__)) await self.log(f"Error rotating server icon:```\n{error}\n```") async def log(self, msg): await self.bot.get_channel(PLAN_Z).send(msg) @tasks.loop(hours=1) async def check_if_new_week(self): # TODO pass @commands.group(invoke_without_command=True) async def icons(self, ctx): """Base command for controlling server icon.""" images = os.listdir(IMG_DIR) count = len(images) await ctx.send(f"Found `{count}` total images: ```py\n{images}\n```") @icons.command() async def rotate(self, ctx): """Rotate to the next server icon.""" await self.rotate_server_icon() @icons.command() async def upload(self, ctx): """Add a new image to the icon folder.""" attachment = ctx.message.attachments[0] filename = f"{IMG_DIR}/{attachment.filename}" await attachment.save(filename) await ctx.send(f"Saved as `{filename}`.") def setup(bot): bot.add_cog(ServerIcon(bot))
archive/server_icon.py
import os import random import traceback import discord from discord.ext import commands, tasks GUILD = 384811165949231104 IMG_DIR = './data/server-icons' PLAN_Z = 507429352720433152 def find_file(i): images = os.listdir(IMG_DIR) for img_name in images: if img_name.startswith(str(i)): return f'{IMG_DIR}/{img_name}' return def shuffle_server_icons(): names = list(range(len(os.listdir(IMG_DIR)))) random.shuffle(names) for img_name in os.listdir(IMG_DIR): ext = img_name.split('.')[-1] os.rename(f'{IMG_DIR}/{img_name}', f'{IMG_DIR}/{names.pop()}.{ext}') class ServerIcon(commands.Cog): """Automatic server icon rotation.""" def __init__(self, bot): self.bot = bot # self.check_if_new_week.start() async def cog_command_error(self, ctx, error): if not isinstance(error, commands.CheckFailure): await ctx.send(f"```py\n{error.__class__.__name__}: {error}\n```") async def rotate_server_icon(self): try: guild = self.bot.get_guild(GUILD) img = random.choice(os.listdir(IMG_DIR)) img_path = f"{IMG_DIR}/{img}" with open(img_path, 'rb') as fp: icon = fp.read() await guild.edit(icon=icon) await self.log(f"Set server icon to `{img_path}`.") except Exception as e: error = ''.join(traceback.format_exception(e.__class__, e, e.__traceback__)) await self.log(f"Error rotating server icon:```\n{error}\n```") async def log(self, msg): await self.bot.get_channel(PLAN_Z).send(msg) @tasks.loop(hours=1) async def check_if_new_week(self): # TODO pass @commands.group(invoke_without_command=True) async def icons(self, ctx): """Base command for controlling server icon.""" images = os.listdir(IMG_DIR) count = len(images) await ctx.send(f"Found `{count}` total images: ```py\n{images}\n```") @icons.command() async def rotate(self, ctx): """Rotate to the next server icon.""" await self.rotate_server_icon() @icons.command() async def upload(self, ctx): """Add a new image to the icon folder.""" attachment = ctx.message.attachments[0] filename = f"{IMG_DIR}/{attachment.filename}" await attachment.save(filename) await ctx.send(f"Saved as `{filename}`.") def setup(bot): bot.add_cog(ServerIcon(bot))
0.386069
0.2296
import numpy as np import histo_funcs as hf from scipy.interpolate import interp1d def get_shifts(ref, N, max_shift=150, global_shift_fun=None): """ This computes the optimal shift between a 1d reference array and the columns of a 2d data array using an fft based cross correlation. The optimal shift is assumed to be where the cross correlation is maximal. Because no padding or normalization is applied, this works best for relatively small shifts. This is explicitly enforced by the ``max_shift`` parameter. Parameters ---------- ref : real numeric 1d array (shape is nx1) The reference array. Should be in a nx1 column array. N : real numeric 2d array (shape is nxm) The data array. Each column of this array will be cross-correlated to the reference array using an fft. max_shift : int (default is 150) The maximum number of bins that are searched for the cross-correlation. The cross correlation is set to zero for lags less than -max_shift and greater than +max_shift. global_shift_fun : function handle (default is None) This function applies an additional subtractive shift to the returned shift array. I generally set this to numpy.mean or numpy.median, but more complex shift functions could be used (including lambdas). Returns ------- shifts : numeric 1d array The shift (in units of bin index) that was required to align each column of data to the reference spectrum. """ # Note: Use real valued fft to improve speed/memory # FFT the ref and data arrays rfft_ref = np.fft.rfft(ref, axis=1) rfft_N = np.fft.rfft(N, axis=1) # Compute the cross-correlation and take the inverse fft xc = np.fft.irfft(rfft_N*np.conj(rfft_ref), axis=1) # Set the cross correlation to zero for lags greater than max_shift xc[:, max_shift:xc.shape[1]-max_shift] = 0 # Find the lags corresponding to the maximum of the cross correlation and # then shift them to correspond to the appropriate origin. max_idxs = np.argmax(xc, axis=1) max_idxs[max_idxs > xc.shape[1]//2] = \ max_idxs[max_idxs > xc.shape[1]//2] - xc.shape[1] # Apply a global_shift_fun shift if specified if global_shift_fun is not None: shifts = max_idxs - global_shift_fun(max_idxs) else: shifts = max_idxs return shifts def get_all_scale_coeffs(event_dat, max_scale=1.1, roi=None, cts_per_chunk=2**10, delta_logdat=5e-4): """ This attempts to best align event data. The basic assumption is that if the ``event_dat`` is binned into a 2d history (histogram) then there are clearly defined features (i.e. peaks) that will shift around in a systematic manner. When this data is projected onto a single dimension then any features (peaks) will be broader than they really should be. This algorithm discretizes the event_dat into `chunks' and attempts to align each chunk to a reference dataset using a scalar multiplicative coefficient. The reference dataset is the middle 50% of the ``event_dat``. The alignment is performed using a logarithm based cross correlation approach. Two iterations of this algorithm are performed before the result is returned. In all tests performed thus far a single iteration was sufficient however we used two iterations in an abundance of caution. Parameters ---------- event_dat : real float 1d array Event data. Typically the data is either the mass-to-charge or time-of-flight of each event. The ordering of the data is assumed to be chronological (i.e. the order in which they were detected). max_scale : real float (default is 1.1) The maximum possible scale factor allowed (relative to the reference data) roi : real numeric list or array (default is [0.5,200]) The domain that the data should be evaluated over. Specified as [min, max] values. cts_per_chunk : int (default is 1024) The number of events to be collected into a single `chunk' of data. delta_logdat : real float (default is 5e-4) The discretization of the log(data) over the roi specified. Smaller deltas are more time/memory intensive. For deltas much less than one, this effectively gives a discretization/resolution of the multiplicative factor of 1+delta_logdat. For the atom probe data I have worked with, the noise on the shift is on the order of 1e-3 and so setting the delta to be smaller than this, ensures that the discretization error is not a significant problem. Returns ------- eventwise_scales : real float array An array that contains the computed scale factor for each event that best aligns the data. To correct the data, just divide the event_dat array by the eventwise_scales array. """ if roi is None: roi = [0.5, 200] log_roi = np.log(roi) # Take the log of data logdat = np.log(event_dat) # Create the histogram. Compute centers and delta y N, seq_edges, logdat_edges = \ hf.create_histogram(logdat, roi=log_roi, cts_per_chunk=cts_per_chunk, delta_dat=delta_logdat) seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges) # print('specified delta_logdat = '+str(delta_logdat)) delta_logdat = logdat_edges[1]-logdat_edges[0] # print('actual delta_logdat = '+str(delta_logdat)) # Initialize the total eventwise log(dat) shift eventwise_logdat_shifts = np.zeros(event_dat.size) # Do one iteration with the center 50% of the data as a reference # Note: Make it is 2d (even though it is just a single column array) ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :] # Get the maximum possible shift in bins. max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat)) # Determine the chunkwise shifts chunkwise_shifts0 = delta_logdat*get_shifts(ref, N, max_shift=max_pixel_shift, global_shift_fun=np.mean) # Interpolate (linear) from chunkwise to eventwise shifts f = interp1d(seq_centers, chunkwise_shifts0, fill_value='extrapolate') # Accumulate the shift for the first iteration. eventwise_logdat_shifts += f(np.arange(event_dat.size)) # Correct the log(data) logdat_corr = logdat - eventwise_logdat_shifts # Recompute the histogram with newly corrected log(data) N, seq_edges, logdat_edges = \ hf.create_histogram(logdat_corr, roi=log_roi, cts_per_chunk=cts_per_chunk, delta_dat=delta_logdat) seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges) delta_logdat = logdat_edges[1]-logdat_edges[0] # Use the center 50% of the data as a reference # Note: Make it is 2d (even though it is just a single column array) ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :] # Get the maximum possible shift in bins. max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat)) # Determine the chunkwise shifts chunkwise_shifts1 = delta_logdat*get_shifts(ref, N, max_shift=max_pixel_shift, global_shift_fun=np.mean) # Interpolate to get eventwise shifts f = interp1d(seq_centers, chunkwise_shifts1, fill_value='extrapolate') # Accumulate the shift for the second iteration. eventwise_logdat_shifts += f(np.arange(event_dat.size)) # Compute total eventwise shifts for output eventwise_scales = np.exp(eventwise_logdat_shifts) # # Uncomment this to see the relative importance of the two iterations # import matplotlib.pyplot as plt # plt.figure() # plt.plot(np.exp(chunkwise_shifts0), label='iter 0') # plt.plot(np.exp(chunkwise_shifts1), label='iter 1') # plt.legend() return eventwise_scales
SiO2/SEDcorr/sed_corr.py
import numpy as np import histo_funcs as hf from scipy.interpolate import interp1d def get_shifts(ref, N, max_shift=150, global_shift_fun=None): """ This computes the optimal shift between a 1d reference array and the columns of a 2d data array using an fft based cross correlation. The optimal shift is assumed to be where the cross correlation is maximal. Because no padding or normalization is applied, this works best for relatively small shifts. This is explicitly enforced by the ``max_shift`` parameter. Parameters ---------- ref : real numeric 1d array (shape is nx1) The reference array. Should be in a nx1 column array. N : real numeric 2d array (shape is nxm) The data array. Each column of this array will be cross-correlated to the reference array using an fft. max_shift : int (default is 150) The maximum number of bins that are searched for the cross-correlation. The cross correlation is set to zero for lags less than -max_shift and greater than +max_shift. global_shift_fun : function handle (default is None) This function applies an additional subtractive shift to the returned shift array. I generally set this to numpy.mean or numpy.median, but more complex shift functions could be used (including lambdas). Returns ------- shifts : numeric 1d array The shift (in units of bin index) that was required to align each column of data to the reference spectrum. """ # Note: Use real valued fft to improve speed/memory # FFT the ref and data arrays rfft_ref = np.fft.rfft(ref, axis=1) rfft_N = np.fft.rfft(N, axis=1) # Compute the cross-correlation and take the inverse fft xc = np.fft.irfft(rfft_N*np.conj(rfft_ref), axis=1) # Set the cross correlation to zero for lags greater than max_shift xc[:, max_shift:xc.shape[1]-max_shift] = 0 # Find the lags corresponding to the maximum of the cross correlation and # then shift them to correspond to the appropriate origin. max_idxs = np.argmax(xc, axis=1) max_idxs[max_idxs > xc.shape[1]//2] = \ max_idxs[max_idxs > xc.shape[1]//2] - xc.shape[1] # Apply a global_shift_fun shift if specified if global_shift_fun is not None: shifts = max_idxs - global_shift_fun(max_idxs) else: shifts = max_idxs return shifts def get_all_scale_coeffs(event_dat, max_scale=1.1, roi=None, cts_per_chunk=2**10, delta_logdat=5e-4): """ This attempts to best align event data. The basic assumption is that if the ``event_dat`` is binned into a 2d history (histogram) then there are clearly defined features (i.e. peaks) that will shift around in a systematic manner. When this data is projected onto a single dimension then any features (peaks) will be broader than they really should be. This algorithm discretizes the event_dat into `chunks' and attempts to align each chunk to a reference dataset using a scalar multiplicative coefficient. The reference dataset is the middle 50% of the ``event_dat``. The alignment is performed using a logarithm based cross correlation approach. Two iterations of this algorithm are performed before the result is returned. In all tests performed thus far a single iteration was sufficient however we used two iterations in an abundance of caution. Parameters ---------- event_dat : real float 1d array Event data. Typically the data is either the mass-to-charge or time-of-flight of each event. The ordering of the data is assumed to be chronological (i.e. the order in which they were detected). max_scale : real float (default is 1.1) The maximum possible scale factor allowed (relative to the reference data) roi : real numeric list or array (default is [0.5,200]) The domain that the data should be evaluated over. Specified as [min, max] values. cts_per_chunk : int (default is 1024) The number of events to be collected into a single `chunk' of data. delta_logdat : real float (default is 5e-4) The discretization of the log(data) over the roi specified. Smaller deltas are more time/memory intensive. For deltas much less than one, this effectively gives a discretization/resolution of the multiplicative factor of 1+delta_logdat. For the atom probe data I have worked with, the noise on the shift is on the order of 1e-3 and so setting the delta to be smaller than this, ensures that the discretization error is not a significant problem. Returns ------- eventwise_scales : real float array An array that contains the computed scale factor for each event that best aligns the data. To correct the data, just divide the event_dat array by the eventwise_scales array. """ if roi is None: roi = [0.5, 200] log_roi = np.log(roi) # Take the log of data logdat = np.log(event_dat) # Create the histogram. Compute centers and delta y N, seq_edges, logdat_edges = \ hf.create_histogram(logdat, roi=log_roi, cts_per_chunk=cts_per_chunk, delta_dat=delta_logdat) seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges) # print('specified delta_logdat = '+str(delta_logdat)) delta_logdat = logdat_edges[1]-logdat_edges[0] # print('actual delta_logdat = '+str(delta_logdat)) # Initialize the total eventwise log(dat) shift eventwise_logdat_shifts = np.zeros(event_dat.size) # Do one iteration with the center 50% of the data as a reference # Note: Make it is 2d (even though it is just a single column array) ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :] # Get the maximum possible shift in bins. max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat)) # Determine the chunkwise shifts chunkwise_shifts0 = delta_logdat*get_shifts(ref, N, max_shift=max_pixel_shift, global_shift_fun=np.mean) # Interpolate (linear) from chunkwise to eventwise shifts f = interp1d(seq_centers, chunkwise_shifts0, fill_value='extrapolate') # Accumulate the shift for the first iteration. eventwise_logdat_shifts += f(np.arange(event_dat.size)) # Correct the log(data) logdat_corr = logdat - eventwise_logdat_shifts # Recompute the histogram with newly corrected log(data) N, seq_edges, logdat_edges = \ hf.create_histogram(logdat_corr, roi=log_roi, cts_per_chunk=cts_per_chunk, delta_dat=delta_logdat) seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges) delta_logdat = logdat_edges[1]-logdat_edges[0] # Use the center 50% of the data as a reference # Note: Make it is 2d (even though it is just a single column array) ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :] # Get the maximum possible shift in bins. max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat)) # Determine the chunkwise shifts chunkwise_shifts1 = delta_logdat*get_shifts(ref, N, max_shift=max_pixel_shift, global_shift_fun=np.mean) # Interpolate to get eventwise shifts f = interp1d(seq_centers, chunkwise_shifts1, fill_value='extrapolate') # Accumulate the shift for the second iteration. eventwise_logdat_shifts += f(np.arange(event_dat.size)) # Compute total eventwise shifts for output eventwise_scales = np.exp(eventwise_logdat_shifts) # # Uncomment this to see the relative importance of the two iterations # import matplotlib.pyplot as plt # plt.figure() # plt.plot(np.exp(chunkwise_shifts0), label='iter 0') # plt.plot(np.exp(chunkwise_shifts1), label='iter 1') # plt.legend() return eventwise_scales
0.897852
0.75665
from textwrap import dedent import unittest from graphql import parse from ...schema_transformation.utils import InvalidTypeNameError, SchemaStructureError, check_ast_schema_is_valid class TestCheckSchemaValid(unittest.TestCase): def test_missing_type_schema(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_schema_extension(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } extend type Human { age: Int } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_input_type_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { id: String } input MessageInput { content: String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_mutation_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery mutation: SchemaMutation } type SchemaQuery { id: String } type SchemaMutation { addId(id: String): String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_subscription_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery subscription: SchemaSubscription } type SchemaQuery { id: String } type SchemaSubscription { getId: String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_inconsistent_root_field_name(self): schema_string = dedent( """\ schema { query: SchemaQuery } type Human1 { id: String } type Human2 { id: String } type SchemaQuery { human1: Human1 human2: Human2 } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_double_underscore_name(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { __Human: __Human } type __Human { id: String } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_type(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } type __Type { id: String } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_enum(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } enum __Type { ENUM1 ENUM2 } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_scalar(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } scalar __Type """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string))
graphql_compiler/tests/schema_transformation_tests/test_check_schema_valid.py
from textwrap import dedent import unittest from graphql import parse from ...schema_transformation.utils import InvalidTypeNameError, SchemaStructureError, check_ast_schema_is_valid class TestCheckSchemaValid(unittest.TestCase): def test_missing_type_schema(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_schema_extension(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } extend type Human { age: Int } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_input_type_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { id: String } input MessageInput { content: String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_mutation_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery mutation: SchemaMutation } type SchemaQuery { id: String } type SchemaMutation { addId(id: String): String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_subscription_definition(self): schema_string = dedent( """\ schema { query: SchemaQuery subscription: SchemaSubscription } type SchemaQuery { id: String } type SchemaSubscription { getId: String } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_inconsistent_root_field_name(self): schema_string = dedent( """\ schema { query: SchemaQuery } type Human1 { id: String } type Human2 { id: String } type SchemaQuery { human1: Human1 human2: Human2 } """ ) with self.assertRaises(SchemaStructureError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_double_underscore_name(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { __Human: __Human } type __Human { id: String } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_type(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } type __Type { id: String } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_enum(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } enum __Type { ENUM1 ENUM2 } """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string)) def test_illegal_reserved_name_scalar(self): schema_string = dedent( """\ schema { query: SchemaQuery } type SchemaQuery { Human: Human } type Human { id: String } scalar __Type """ ) with self.assertRaises(InvalidTypeNameError): check_ast_schema_is_valid(parse(schema_string))
0.525612
0.597579
import sys from itertools import product import iris import iris.quickplot as qplt import matplotlib.pyplot as plt import numpy as np import pandas as pd from remake import Task, TaskControl, remake_task_control from cosmic import util from cosmic.config import CONSTRAINT_ASIA, PATHS from orog_precip_paths import (land_sea_mask, extended_rclim_mask, precip_path_tpl, diag_orog_precip_path_tpl, diag_orog_precip_frac_path_tpl, diag_combine_frac_path, fmtp) def calc_orog_precip(inputs, outputs, index_month): extended_rclim_mask = iris.load_cube(str(inputs['extended_rclim_mask']), CONSTRAINT_ASIA) lsm_asia = iris.load_cube(str(inputs['land_sea_mask']), CONSTRAINT_ASIA) precip_asia = iris.load_cube(str(inputs['precip'])) precip_asia_mean = precip_asia.collapsed('time', iris.analysis.MEAN) # Need to regrid to mask resolution. lsm_asia_coarse = util.regrid(lsm_asia, extended_rclim_mask) precip_asia_mean_coarse = util.regrid(precip_asia_mean, extended_rclim_mask) orog_precip_asia = precip_asia_mean_coarse.copy() orog_precip_asia.rename('orog_' + precip_asia_mean_coarse.name()) nonorog_precip_asia = precip_asia_mean_coarse.copy() nonorog_precip_asia.rename('non_orog_' + precip_asia_mean_coarse.name()) ocean_precip_asia = precip_asia_mean_coarse.copy() ocean_precip_asia.rename('ocean_' + precip_asia_mean_coarse.name()) orog_precip_asia.data = (precip_asia_mean_coarse.data * lsm_asia_coarse.data * extended_rclim_mask[index_month].data) nonorog_precip_asia.data = (precip_asia_mean_coarse.data * lsm_asia_coarse.data * (1 - extended_rclim_mask[index_month].data)) ocean_precip_asia.data = (precip_asia_mean_coarse.data * (1 - lsm_asia_coarse.data)) iris.save(iris.cube.CubeList([orog_precip_asia, nonorog_precip_asia, ocean_precip_asia]), str(outputs[0])) def calc_orog_precip_fracs(inputs, outputs, index_month): # TODO: area weighting. orog_mask = iris.load_cube(str(inputs['extended_rclim_mask'])) lsm = iris.load_cube(str(inputs['land_sea_mask'])) orog_precip_cubes = iris.load(str(inputs['orog_precip'])) lsm_coarse = util.regrid(lsm, orog_mask) orog_mask_asia = orog_mask.extract(CONSTRAINT_ASIA) lsm_coarse_asia = lsm_coarse.extract(CONSTRAINT_ASIA) orog_precip = orog_precip_cubes.extract_strict('orog_precipitation_flux') non_orog_precip = orog_precip_cubes.extract_strict('non_orog_precipitation_flux') land_precip = orog_precip + non_orog_precip ocean_precip = orog_precip_cubes.extract_strict('ocean_precipitation_flux') orog_frac = (orog_mask_asia[index_month].data * lsm_coarse_asia.data).sum() / lsm_coarse_asia.data.sum() non_orog_frac = ((1 - orog_mask_asia[index_month].data) * lsm_coarse_asia.data).sum() / lsm_coarse_asia.data.sum() land_precip_total = land_precip.data.sum() ocean_precip_total = ocean_precip.data.sum() orog_precip_total = orog_precip.data.sum() non_orog_precip_total = non_orog_precip.data.sum() land_precip_frac = land_precip_total / (ocean_precip_total + land_precip_total) orog_precip_frac = orog_precip_total / land_precip_total non_orog_precip_frac = non_orog_precip_total / land_precip_total df = pd.DataFrame({ 'orog_frac': [orog_frac], 'non_orog_frac': [non_orog_frac], 'land_total': [land_precip_total], 'ocean_total': [ocean_precip_total], 'land_frac': [land_precip_frac], 'orog_total': [orog_precip_total], 'non_orog_total': [non_orog_precip_total], 'orog_precip_frac': [orog_precip_frac], 'non_orog_precip_frac': [non_orog_precip_frac], }) df.to_hdf(str(outputs[0]), 'orog_fracs') def combine_orog_precip_fracs(inputs, outputs, variables, columns): dfs = [] for input_path in inputs: df = pd.read_hdf(str(input_path)) dfs.append(df) df_combined = pd.concat(dfs, ignore_index=True) df_combined['dataset'] = [str(p) for p in inputs] df_combined = pd.concat([df_combined, pd.DataFrame(variables, columns=columns)], axis=1) df_combined.to_hdf(str(outputs[0]), 'combined_orog_fracs') @remake_task_control def gen_task_ctrl(): tc = TaskControl(__file__) # /gws/nopw/j04/cosmic/mmuetz/data/era_interim_orog_precip years = [2006] # years = [2005, 2006, 2007, 2008] models = ['al508', 'ak543'] months = [6, 7, 8] for model, year, month in product(models, years, months): # al508a.p9200606.asia_precip.nc precip_path = fmtp(precip_path_tpl, model=model, year=year, month=month) orog_precip_inputs = { 'extended_rclim_mask': extended_rclim_mask, 'land_sea_mask': land_sea_mask, 'precip': precip_path } diag_orog_precip_path = fmtp(diag_orog_precip_path_tpl, model=model, year=year, month=month) tc.add(Task(calc_orog_precip, orog_precip_inputs, [diag_orog_precip_path], func_args=(month - 1, ))) orog_precip_fracs_inputs = { 'extended_rclim_mask': extended_rclim_mask, 'land_sea_mask': land_sea_mask, 'orog_precip': diag_orog_precip_path } diag_orog_precip_frac_path = fmtp(diag_orog_precip_frac_path_tpl, model=model, year=year, month=month) tc.add(Task(calc_orog_precip_fracs, orog_precip_fracs_inputs, [diag_orog_precip_frac_path], func_args=(month - 1, ))) variables = list(product(models, months)) columns = ['model', 'month'] combine_inputs = [fmtp(diag_orog_precip_frac_path_tpl, model=model, year=year, month=month) for model, month in variables] combine_fracs_output = [diag_combine_frac_path] tc.add(Task(combine_orog_precip_fracs, combine_inputs, combine_fracs_output, func_args=(variables, columns) )) return tc
ctrl/WP2_analysis/orog_precip/diagnose_orog_mask.py
import sys from itertools import product import iris import iris.quickplot as qplt import matplotlib.pyplot as plt import numpy as np import pandas as pd from remake import Task, TaskControl, remake_task_control from cosmic import util from cosmic.config import CONSTRAINT_ASIA, PATHS from orog_precip_paths import (land_sea_mask, extended_rclim_mask, precip_path_tpl, diag_orog_precip_path_tpl, diag_orog_precip_frac_path_tpl, diag_combine_frac_path, fmtp) def calc_orog_precip(inputs, outputs, index_month): extended_rclim_mask = iris.load_cube(str(inputs['extended_rclim_mask']), CONSTRAINT_ASIA) lsm_asia = iris.load_cube(str(inputs['land_sea_mask']), CONSTRAINT_ASIA) precip_asia = iris.load_cube(str(inputs['precip'])) precip_asia_mean = precip_asia.collapsed('time', iris.analysis.MEAN) # Need to regrid to mask resolution. lsm_asia_coarse = util.regrid(lsm_asia, extended_rclim_mask) precip_asia_mean_coarse = util.regrid(precip_asia_mean, extended_rclim_mask) orog_precip_asia = precip_asia_mean_coarse.copy() orog_precip_asia.rename('orog_' + precip_asia_mean_coarse.name()) nonorog_precip_asia = precip_asia_mean_coarse.copy() nonorog_precip_asia.rename('non_orog_' + precip_asia_mean_coarse.name()) ocean_precip_asia = precip_asia_mean_coarse.copy() ocean_precip_asia.rename('ocean_' + precip_asia_mean_coarse.name()) orog_precip_asia.data = (precip_asia_mean_coarse.data * lsm_asia_coarse.data * extended_rclim_mask[index_month].data) nonorog_precip_asia.data = (precip_asia_mean_coarse.data * lsm_asia_coarse.data * (1 - extended_rclim_mask[index_month].data)) ocean_precip_asia.data = (precip_asia_mean_coarse.data * (1 - lsm_asia_coarse.data)) iris.save(iris.cube.CubeList([orog_precip_asia, nonorog_precip_asia, ocean_precip_asia]), str(outputs[0])) def calc_orog_precip_fracs(inputs, outputs, index_month): # TODO: area weighting. orog_mask = iris.load_cube(str(inputs['extended_rclim_mask'])) lsm = iris.load_cube(str(inputs['land_sea_mask'])) orog_precip_cubes = iris.load(str(inputs['orog_precip'])) lsm_coarse = util.regrid(lsm, orog_mask) orog_mask_asia = orog_mask.extract(CONSTRAINT_ASIA) lsm_coarse_asia = lsm_coarse.extract(CONSTRAINT_ASIA) orog_precip = orog_precip_cubes.extract_strict('orog_precipitation_flux') non_orog_precip = orog_precip_cubes.extract_strict('non_orog_precipitation_flux') land_precip = orog_precip + non_orog_precip ocean_precip = orog_precip_cubes.extract_strict('ocean_precipitation_flux') orog_frac = (orog_mask_asia[index_month].data * lsm_coarse_asia.data).sum() / lsm_coarse_asia.data.sum() non_orog_frac = ((1 - orog_mask_asia[index_month].data) * lsm_coarse_asia.data).sum() / lsm_coarse_asia.data.sum() land_precip_total = land_precip.data.sum() ocean_precip_total = ocean_precip.data.sum() orog_precip_total = orog_precip.data.sum() non_orog_precip_total = non_orog_precip.data.sum() land_precip_frac = land_precip_total / (ocean_precip_total + land_precip_total) orog_precip_frac = orog_precip_total / land_precip_total non_orog_precip_frac = non_orog_precip_total / land_precip_total df = pd.DataFrame({ 'orog_frac': [orog_frac], 'non_orog_frac': [non_orog_frac], 'land_total': [land_precip_total], 'ocean_total': [ocean_precip_total], 'land_frac': [land_precip_frac], 'orog_total': [orog_precip_total], 'non_orog_total': [non_orog_precip_total], 'orog_precip_frac': [orog_precip_frac], 'non_orog_precip_frac': [non_orog_precip_frac], }) df.to_hdf(str(outputs[0]), 'orog_fracs') def combine_orog_precip_fracs(inputs, outputs, variables, columns): dfs = [] for input_path in inputs: df = pd.read_hdf(str(input_path)) dfs.append(df) df_combined = pd.concat(dfs, ignore_index=True) df_combined['dataset'] = [str(p) for p in inputs] df_combined = pd.concat([df_combined, pd.DataFrame(variables, columns=columns)], axis=1) df_combined.to_hdf(str(outputs[0]), 'combined_orog_fracs') @remake_task_control def gen_task_ctrl(): tc = TaskControl(__file__) # /gws/nopw/j04/cosmic/mmuetz/data/era_interim_orog_precip years = [2006] # years = [2005, 2006, 2007, 2008] models = ['al508', 'ak543'] months = [6, 7, 8] for model, year, month in product(models, years, months): # al508a.p9200606.asia_precip.nc precip_path = fmtp(precip_path_tpl, model=model, year=year, month=month) orog_precip_inputs = { 'extended_rclim_mask': extended_rclim_mask, 'land_sea_mask': land_sea_mask, 'precip': precip_path } diag_orog_precip_path = fmtp(diag_orog_precip_path_tpl, model=model, year=year, month=month) tc.add(Task(calc_orog_precip, orog_precip_inputs, [diag_orog_precip_path], func_args=(month - 1, ))) orog_precip_fracs_inputs = { 'extended_rclim_mask': extended_rclim_mask, 'land_sea_mask': land_sea_mask, 'orog_precip': diag_orog_precip_path } diag_orog_precip_frac_path = fmtp(diag_orog_precip_frac_path_tpl, model=model, year=year, month=month) tc.add(Task(calc_orog_precip_fracs, orog_precip_fracs_inputs, [diag_orog_precip_frac_path], func_args=(month - 1, ))) variables = list(product(models, months)) columns = ['model', 'month'] combine_inputs = [fmtp(diag_orog_precip_frac_path_tpl, model=model, year=year, month=month) for model, month in variables] combine_fracs_output = [diag_combine_frac_path] tc.add(Task(combine_orog_precip_fracs, combine_inputs, combine_fracs_output, func_args=(variables, columns) )) return tc
0.209712
0.340924
from __future__ import print_function import os import math import tensorflow as tf import horovod.tensorflow as hvd from model import efficientnet_model from utils import dataset_factory, hvd_utils, callbacks, preprocessing __all__ = ['get_optimizer_params', 'get_metrics', 'get_learning_rate_params', 'build_model_params', 'get_models', 'build_augmenter_params', \ 'get_image_size_from_model', 'get_dataset_builders', 'build_stats', 'parse_inference_input', 'preprocess_image_files'] def get_optimizer_params(name, decay, epsilon, momentum, moving_average_decay, nesterov, beta_1, beta_2): return { 'name': name, 'decay': decay, 'epsilon': epsilon, 'momentum': momentum, 'moving_average_decay': moving_average_decay, 'nesterov': nesterov, 'beta_1': beta_1, 'beta_2': beta_2 } def get_metrics(one_hot: bool): """Get a dict of available metrics to track.""" if one_hot: return { # (name, metric_fn) 'acc': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.TopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } else: return { # (name, metric_fn) 'acc': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.SparseTopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } def get_learning_rate_params(name, initial_lr, decay_epochs, decay_rate, warmup_epochs): return { 'name':name, 'initial_lr': initial_lr, 'decay_epochs': decay_epochs, 'decay_rate': decay_rate, 'warmup_epochs': warmup_epochs, 'examples_per_epoch': None, 'boundaries': None, 'multipliers': None, 'scale_by_batch_size': 1./128., 'staircase': True } def build_model_params(model_name, is_training, batch_norm, num_classes, activation, dtype, weight_decay, weight_init): return { 'model_name': model_name, 'model_weights_path': '', 'weights_format': 'saved_model', 'overrides': { 'is_training': is_training, 'batch_norm': batch_norm, 'rescale_input': True, 'num_classes': num_classes, 'weight_decay': weight_decay, 'activation': activation, 'dtype': dtype, 'weight_init': weight_init } } def get_models(): """Returns the mapping from model type name to Keras model.""" return { 'efficientnet': efficientnet_model.EfficientNet.from_name, } def build_augmenter_params(augmenter_name, cutout_const, translate_const, num_layers, magnitude, autoaugmentation_name): if augmenter_name is None or augmenter_name not in ['randaugment', 'autoaugment']: return {} augmenter_params = {} if cutout_const is not None: augmenter_params['cutout_const'] = cutout_const if translate_const is not None: augmenter_params['translate_const'] = translate_const if augmenter_name == 'randaugment': if num_layers is not None: augmenter_params['num_layers'] = num_layers if magnitude is not None: augmenter_params['magnitude'] = magnitude if augmenter_name == 'autoaugment': if autoaugmentation_name is not None: augmenter_params['autoaugmentation_name'] = autoaugmentation_name return augmenter_params def get_image_size_from_model(arch): """If the given model has a preferred image size, return it.""" if 'efficientnet' in arch: efficientnet_name = arch if efficientnet_name in efficientnet_model.MODEL_CONFIGS: return efficientnet_model.MODEL_CONFIGS[efficientnet_name]['resolution'] return None def get_dataset_builders(params, one_hot): """Create and return train and validation dataset builders.""" if hvd.size() > 1: num_gpus = hvd.size() else: num_devices = 1 image_size = get_image_size_from_model(params.arch) print("Image size {}".format(image_size)) print("Train batch size {}".format(params.train_batch_size)) builders = [] validation_dataset_builder = None train_dataset_builder = None if "train" in params.mode: train_dataset_builder = dataset_factory.Dataset(data_dir=params.data_dir, index_file_dir=params.index_file, split='train', num_classes=params.num_classes, image_size=image_size, batch_size=params.train_batch_size, one_hot=one_hot, use_dali=params.use_dali, augmenter=params.augmenter_name, augmenter_params=build_augmenter_params(params.augmenter_name, params.cutout_const, params.translate_const, params.num_layers, params.magnitude, params.autoaugmentation_name), mixup_alpha=params.mixup_alpha ) if "eval" in params.mode: validation_dataset_builder = dataset_factory.Dataset(data_dir=params.data_dir, index_file_dir=params.index_file, split='validation', num_classes=params.num_classes, image_size=image_size, batch_size=params.eval_batch_size, one_hot=one_hot, use_dali=params.use_dali_eval) builders.append(train_dataset_builder) builders.append(validation_dataset_builder) return builders def build_stats(history, validation_output, train_callbacks, eval_callback, logger): stats = {} if validation_output: stats['eval_loss'] = float(validation_output[0]) stats['eval_accuracy_top_1'] = float(validation_output[1]) stats['eval_accuracy_top_5'] = float(validation_output[2]) #This part is train loss on GPU_0 if history and history.history: train_hist = history.history #Gets final loss from training. stats['training_loss'] = float(hvd.allreduce(tf.constant(train_hist['loss'][-1], dtype=tf.float32), average=True)) # Gets top_1 training accuracy. if 'categorical_accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['categorical_accuracy'][-1], dtype=tf.float32), average=True)) elif 'sparse_categorical_accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['sparse_categorical_accuracy'][-1], dtype=tf.float32), average=True)) elif 'accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['accuracy'][-1], dtype=tf.float32), average=True)) stats['training_accuracy_top_5'] = float(hvd.allreduce(tf.constant(train_hist['top_5_accuracy'][-1], dtype=tf.float32), average=True)) # Look for the time history callback which was used during keras.fit if train_callbacks: for callback in train_callbacks: if isinstance(callback, callbacks.TimeHistory): if callback.epoch_runtime_log: stats['avg_exp_per_second_training'] = callback.average_examples_per_second stats['avg_exp_per_second_training_per_GPU'] = callback.average_examples_per_second / hvd.size() if eval_callback: stats['avg_exp_per_second_eval'] = float(eval_callback.average_examples_per_second) * hvd.size() stats['avg_exp_per_second_eval_per_GPU'] = float(eval_callback.average_examples_per_second) stats['avg_time_per_exp_eval'] = 1000./stats['avg_exp_per_second_eval'] batch_time = eval_callback.batch_time batch_time.sort() latency_pct_per_batch = sum( batch_time[:-1] ) / int( len(batch_time) - 1 ) stats['latency_pct'] = 1000.0 * latency_pct_per_batch latency_90pct_per_batch = sum( batch_time[:int( 0.9 * len(batch_time) )] ) / int( 0.9 * len(batch_time) ) stats['latency_90pct'] = 1000.0 * latency_90pct_per_batch latency_95pct_per_batch = sum( batch_time[:int( 0.95 * len(batch_time) )] ) / int( 0.95 * len(batch_time) ) stats['latency_95pct'] = 1000.0 * latency_95pct_per_batch latency_99pct_per_batch = sum( batch_time[:int( 0.99 * len(batch_time) )] ) / int( 0.99 * len(batch_time) ) stats['latency_99pct'] = 1000.0 * latency_99pct_per_batch if not hvd_utils.is_using_hvd() or hvd.rank() == 0: logger.log(step=(), data=stats) def preprocess_image_files(directory_name, arch, batch_size, num_channels=3, dtype=tf.float32): image_size = get_image_size_from_model(arch) datagen = tf.keras.preprocessing.image.ImageDataGenerator(data_format="channels_last") images = datagen.flow_from_directory(directory_name, class_mode=None, batch_size=batch_size, target_size=(image_size, image_size), shuffle=False) return images def parse_inference_input(to_predict): filenames = [] image_formats = ['.jpg', '.jpeg', '.JPEG', '.JPG', '.png', '.PNG'] if os.path.isdir(to_predict): filenames = [f for f in os.listdir(to_predict) if os.path.isfile(os.path.join(to_predict, f)) and os.path.splitext(f)[1] in image_formats] elif os.path.isfile(to_predict): filenames.append(to_predict) return filenames
DeepLearningExamples/TensorFlow2/Classification/ConvNets/efficientnet/runtime/runner_utils.py
from __future__ import print_function import os import math import tensorflow as tf import horovod.tensorflow as hvd from model import efficientnet_model from utils import dataset_factory, hvd_utils, callbacks, preprocessing __all__ = ['get_optimizer_params', 'get_metrics', 'get_learning_rate_params', 'build_model_params', 'get_models', 'build_augmenter_params', \ 'get_image_size_from_model', 'get_dataset_builders', 'build_stats', 'parse_inference_input', 'preprocess_image_files'] def get_optimizer_params(name, decay, epsilon, momentum, moving_average_decay, nesterov, beta_1, beta_2): return { 'name': name, 'decay': decay, 'epsilon': epsilon, 'momentum': momentum, 'moving_average_decay': moving_average_decay, 'nesterov': nesterov, 'beta_1': beta_1, 'beta_2': beta_2 } def get_metrics(one_hot: bool): """Get a dict of available metrics to track.""" if one_hot: return { # (name, metric_fn) 'acc': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.CategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.TopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } else: return { # (name, metric_fn) 'acc': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'accuracy': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_1': tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), 'top_5': tf.keras.metrics.SparseTopKCategoricalAccuracy( k=5, name='top_5_accuracy'), } def get_learning_rate_params(name, initial_lr, decay_epochs, decay_rate, warmup_epochs): return { 'name':name, 'initial_lr': initial_lr, 'decay_epochs': decay_epochs, 'decay_rate': decay_rate, 'warmup_epochs': warmup_epochs, 'examples_per_epoch': None, 'boundaries': None, 'multipliers': None, 'scale_by_batch_size': 1./128., 'staircase': True } def build_model_params(model_name, is_training, batch_norm, num_classes, activation, dtype, weight_decay, weight_init): return { 'model_name': model_name, 'model_weights_path': '', 'weights_format': 'saved_model', 'overrides': { 'is_training': is_training, 'batch_norm': batch_norm, 'rescale_input': True, 'num_classes': num_classes, 'weight_decay': weight_decay, 'activation': activation, 'dtype': dtype, 'weight_init': weight_init } } def get_models(): """Returns the mapping from model type name to Keras model.""" return { 'efficientnet': efficientnet_model.EfficientNet.from_name, } def build_augmenter_params(augmenter_name, cutout_const, translate_const, num_layers, magnitude, autoaugmentation_name): if augmenter_name is None or augmenter_name not in ['randaugment', 'autoaugment']: return {} augmenter_params = {} if cutout_const is not None: augmenter_params['cutout_const'] = cutout_const if translate_const is not None: augmenter_params['translate_const'] = translate_const if augmenter_name == 'randaugment': if num_layers is not None: augmenter_params['num_layers'] = num_layers if magnitude is not None: augmenter_params['magnitude'] = magnitude if augmenter_name == 'autoaugment': if autoaugmentation_name is not None: augmenter_params['autoaugmentation_name'] = autoaugmentation_name return augmenter_params def get_image_size_from_model(arch): """If the given model has a preferred image size, return it.""" if 'efficientnet' in arch: efficientnet_name = arch if efficientnet_name in efficientnet_model.MODEL_CONFIGS: return efficientnet_model.MODEL_CONFIGS[efficientnet_name]['resolution'] return None def get_dataset_builders(params, one_hot): """Create and return train and validation dataset builders.""" if hvd.size() > 1: num_gpus = hvd.size() else: num_devices = 1 image_size = get_image_size_from_model(params.arch) print("Image size {}".format(image_size)) print("Train batch size {}".format(params.train_batch_size)) builders = [] validation_dataset_builder = None train_dataset_builder = None if "train" in params.mode: train_dataset_builder = dataset_factory.Dataset(data_dir=params.data_dir, index_file_dir=params.index_file, split='train', num_classes=params.num_classes, image_size=image_size, batch_size=params.train_batch_size, one_hot=one_hot, use_dali=params.use_dali, augmenter=params.augmenter_name, augmenter_params=build_augmenter_params(params.augmenter_name, params.cutout_const, params.translate_const, params.num_layers, params.magnitude, params.autoaugmentation_name), mixup_alpha=params.mixup_alpha ) if "eval" in params.mode: validation_dataset_builder = dataset_factory.Dataset(data_dir=params.data_dir, index_file_dir=params.index_file, split='validation', num_classes=params.num_classes, image_size=image_size, batch_size=params.eval_batch_size, one_hot=one_hot, use_dali=params.use_dali_eval) builders.append(train_dataset_builder) builders.append(validation_dataset_builder) return builders def build_stats(history, validation_output, train_callbacks, eval_callback, logger): stats = {} if validation_output: stats['eval_loss'] = float(validation_output[0]) stats['eval_accuracy_top_1'] = float(validation_output[1]) stats['eval_accuracy_top_5'] = float(validation_output[2]) #This part is train loss on GPU_0 if history and history.history: train_hist = history.history #Gets final loss from training. stats['training_loss'] = float(hvd.allreduce(tf.constant(train_hist['loss'][-1], dtype=tf.float32), average=True)) # Gets top_1 training accuracy. if 'categorical_accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['categorical_accuracy'][-1], dtype=tf.float32), average=True)) elif 'sparse_categorical_accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['sparse_categorical_accuracy'][-1], dtype=tf.float32), average=True)) elif 'accuracy' in train_hist: stats['training_accuracy_top_1'] = float(hvd.allreduce(tf.constant(train_hist['accuracy'][-1], dtype=tf.float32), average=True)) stats['training_accuracy_top_5'] = float(hvd.allreduce(tf.constant(train_hist['top_5_accuracy'][-1], dtype=tf.float32), average=True)) # Look for the time history callback which was used during keras.fit if train_callbacks: for callback in train_callbacks: if isinstance(callback, callbacks.TimeHistory): if callback.epoch_runtime_log: stats['avg_exp_per_second_training'] = callback.average_examples_per_second stats['avg_exp_per_second_training_per_GPU'] = callback.average_examples_per_second / hvd.size() if eval_callback: stats['avg_exp_per_second_eval'] = float(eval_callback.average_examples_per_second) * hvd.size() stats['avg_exp_per_second_eval_per_GPU'] = float(eval_callback.average_examples_per_second) stats['avg_time_per_exp_eval'] = 1000./stats['avg_exp_per_second_eval'] batch_time = eval_callback.batch_time batch_time.sort() latency_pct_per_batch = sum( batch_time[:-1] ) / int( len(batch_time) - 1 ) stats['latency_pct'] = 1000.0 * latency_pct_per_batch latency_90pct_per_batch = sum( batch_time[:int( 0.9 * len(batch_time) )] ) / int( 0.9 * len(batch_time) ) stats['latency_90pct'] = 1000.0 * latency_90pct_per_batch latency_95pct_per_batch = sum( batch_time[:int( 0.95 * len(batch_time) )] ) / int( 0.95 * len(batch_time) ) stats['latency_95pct'] = 1000.0 * latency_95pct_per_batch latency_99pct_per_batch = sum( batch_time[:int( 0.99 * len(batch_time) )] ) / int( 0.99 * len(batch_time) ) stats['latency_99pct'] = 1000.0 * latency_99pct_per_batch if not hvd_utils.is_using_hvd() or hvd.rank() == 0: logger.log(step=(), data=stats) def preprocess_image_files(directory_name, arch, batch_size, num_channels=3, dtype=tf.float32): image_size = get_image_size_from_model(arch) datagen = tf.keras.preprocessing.image.ImageDataGenerator(data_format="channels_last") images = datagen.flow_from_directory(directory_name, class_mode=None, batch_size=batch_size, target_size=(image_size, image_size), shuffle=False) return images def parse_inference_input(to_predict): filenames = [] image_formats = ['.jpg', '.jpeg', '.JPEG', '.JPG', '.png', '.PNG'] if os.path.isdir(to_predict): filenames = [f for f in os.listdir(to_predict) if os.path.isfile(os.path.join(to_predict, f)) and os.path.splitext(f)[1] in image_formats] elif os.path.isfile(to_predict): filenames.append(to_predict) return filenames
0.874507
0.171824
from flask import Flask, render_template, request import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BOARD) pin_list = [12, 16] for pin in pin_list: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) pin_dict = { 12: { 'led_colour': 'Green LED', 'led_state': GPIO.LOW }, 16: { 'led_colour': 'Red LED', 'led_state': GPIO.LOW } } @app.route('/') def main(): for pin in pin_dict: pin_dict[pin]['led_state'] = GPIO.input(pin) template_data = { 'title': 'LEDs current state', 'pin_dict': pin_dict, } return render_template('main.html', **template_data) @app.route('/<led_colour>', methods=['GET', 'POST']) def led_change(led_colour): # soon will be DRY :) if request.method == 'GET': if led_colour == 'red': state_read = GPIO.input(16) if state_read == True: msg = 'Red LED is currently ON.' else: msg = 'Red LED is currently OFF.' template_data = { 'title': 'Red LED', 'message': msg, } return render_template('change_red.html', **template_data) if led_colour == 'green': state_read = GPIO.input(12) if state_read == True: msg = 'Green LED is currently ON.' else: msg = 'Green LED is currently OFF.' template_data = { 'title': 'Green LED', 'message': msg, } return render_template('change_green.html', **template_data) elif request.method =='POST': if led_colour == 'red': if request.form['red_led_change'] == 'red_led': GPIO.output(16, not GPIO.input(16)) state_read = GPIO.input(16) if state_read == True: msg = 'Red LED is currently ON.' else: msg = 'Red LED is currently OFF.' template_data = { 'title': 'Red LED', 'message': msg, } return render_template('change_red.html', **template_data) if led_colour == 'green': if request.form['green_led_change'] == 'green_led': GPIO.output(12, not GPIO.input(12)) state_read = GPIO.input(12) if state_read == True: msg = 'Green LED is currently ON.' else: msg = 'Green LED is currently OFF.' template_data = { 'title': 'Green LED', 'message': msg, } return render_template('change_green.html', **template_data) if __name__ == '__main__': app.run(host='192.168.0.20', port=80, debug=True) GPIO.cleanup()
LED/FLASK/flask_red_green_LED.py
from flask import Flask, render_template, request import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BOARD) pin_list = [12, 16] for pin in pin_list: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) pin_dict = { 12: { 'led_colour': 'Green LED', 'led_state': GPIO.LOW }, 16: { 'led_colour': 'Red LED', 'led_state': GPIO.LOW } } @app.route('/') def main(): for pin in pin_dict: pin_dict[pin]['led_state'] = GPIO.input(pin) template_data = { 'title': 'LEDs current state', 'pin_dict': pin_dict, } return render_template('main.html', **template_data) @app.route('/<led_colour>', methods=['GET', 'POST']) def led_change(led_colour): # soon will be DRY :) if request.method == 'GET': if led_colour == 'red': state_read = GPIO.input(16) if state_read == True: msg = 'Red LED is currently ON.' else: msg = 'Red LED is currently OFF.' template_data = { 'title': 'Red LED', 'message': msg, } return render_template('change_red.html', **template_data) if led_colour == 'green': state_read = GPIO.input(12) if state_read == True: msg = 'Green LED is currently ON.' else: msg = 'Green LED is currently OFF.' template_data = { 'title': 'Green LED', 'message': msg, } return render_template('change_green.html', **template_data) elif request.method =='POST': if led_colour == 'red': if request.form['red_led_change'] == 'red_led': GPIO.output(16, not GPIO.input(16)) state_read = GPIO.input(16) if state_read == True: msg = 'Red LED is currently ON.' else: msg = 'Red LED is currently OFF.' template_data = { 'title': 'Red LED', 'message': msg, } return render_template('change_red.html', **template_data) if led_colour == 'green': if request.form['green_led_change'] == 'green_led': GPIO.output(12, not GPIO.input(12)) state_read = GPIO.input(12) if state_read == True: msg = 'Green LED is currently ON.' else: msg = 'Green LED is currently OFF.' template_data = { 'title': 'Green LED', 'message': msg, } return render_template('change_green.html', **template_data) if __name__ == '__main__': app.run(host='192.168.0.20', port=80, debug=True) GPIO.cleanup()
0.433262
0.088702
from collections import namedtuple from datetime import date, datetime, time from decimal import Context, Decimal, ROUND_HALF_UP from html.parser import HTMLParser from itertools import zip_longest from re import compile, finditer, sub from secrets import choice from string import ascii_letters, digits LOAD_VARIABLE_RE = compile(r"\[[\w()]+\]") LOAD_OPERATOR_RE = compile(r"(?<![<\|>]{1})=|<>") DUMP_VARIABLE_RE = compile(r"record\['\w+'\]") DUMP_OPERATOR_RE = compile(r"==|!=") def dump_field_name(value): """dump field_name""" return value def load_field_name(value): """load field_name""" return value def dump_form_name(value): """dump form_name""" return value def load_form_name(value): """load form_name""" return value def dump_section_header(value): """dump section_header""" return value def load_section_header(value): """load section_header""" return value def dump_field_type(value): """dump field_type""" return value def load_field_type(value): """load field_type""" return value def dump_field_label(value): """dump field_label""" return value def load_field_label(value): """load field_label""" return value def dump_select_choices_or_calculations(value): """dump select_choices_or_calculations""" return value def load_select_choices_or_calculations(value): """load select_choices_or_calculations""" return value def dump_field_note(value): """dump field_note""" return value def load_field_note(value): """load field_note""" return value def dump_text_validation_type_or_show_slider_number(value): """dump text_validation_type_or_show_slider_number""" return value def load_text_validation_type_or_show_slider_number(value): """load text_validation_type_or_show_slider_number""" return value def dump_text_validation_min(value): """dump text_validation_min""" return value def load_text_validation_min(value): """load text_validation_min""" return value def dump_text_validation_max(value): """dump text_validation_max""" return value def load_text_validation_max(value): """load text_validation_max""" return value def dump_identifier(value): """dump identifier""" if value is True: return "y" return "n" def load_identifier(value): """load identifier""" if value == "y": return True return False def dump_branching_logic(value): """dump branching_logic""" if not value: return "" logic_fragments = zip_longest( DUMP_VARIABLE_RE.split(value), [m.group(0) for m in DUMP_VARIABLE_RE.finditer(value)], fillvalue="" ) value = "" for oper_frag, vari_frag in logic_fragments: for match in DUMP_OPERATOR_RE.finditer(oper_frag): ope_str = match.group(0) if ope_str == "==": ope_str = "=" elif ope_str == "!=": ope_str = "<>" oper_frag = ( oper_frag[:match.start()] + ope_str + oper_frag[match.end():] ) if vari_frag: vari_frag = vari_frag.lstrip("record['").rstrip("']") if "___" in vari_frag: vari_frag = "(".join( s for s in vari_frag.split("___") ) + ")" vari_frag = "[" + vari_frag + "]" value += oper_frag + vari_frag return value def load_branching_logic(value): """load branching_logic""" if not value: return "" logic_fragments = zip_longest( LOAD_VARIABLE_RE.split(value), [m.group(0) for m in LOAD_VARIABLE_RE.finditer(value)], fillvalue="" ) value = "" for oper_frag, vari_frag in logic_fragments: for match in LOAD_OPERATOR_RE.finditer(oper_frag): ope_str = match.group(0) if ope_str == "=": ope_str = "==" elif ope_str == "<>": ope_str = "!=" oper_frag = ( oper_frag[:match.start()] + ope_str + oper_frag[match.end():] ) if vari_frag: vari_frag = vari_frag.strip("[]") if "(" in vari_frag and ")" in vari_frag: vari_frag = "___".join( s.strip(")") for s in vari_frag.split("(") ) vari_frag = "record['" + vari_frag + "']" value += oper_frag + vari_frag return value def dump_required_field(value): """dump required_field""" if value is True: return "y" return "n" def load_required_field(value): """load required_field""" if value == "y": return True return False def dump_custom_alignment(value): """dump custom_alignment""" return value def load_custom_alignment(value): """load custom_alignment""" return value def dump_question_number(value): """dump question_number""" return value def load_question_number(value): """load question_number""" return value def dump_matrix_group_name(value): """dump matrix_group_name""" return value def load_matrix_group_name(value): """load matrix_group_name""" return value def dump_matrix_ranking(value): """dump matrix_ranking""" return value def load_matrix_ranking(value): """load matrix_ranking""" return value def dump_field_annotation(value): """dump field_annotation""" return value def load_field_annotation(value): """load field_annotation""" return value dump_map = dict( field_name=dump_field_name, form_name=dump_form_name, section_header=dump_section_header, field_type=dump_field_type, field_label=dump_field_label, select_choices_or_calculations=dump_select_choices_or_calculations, field_note=dump_field_note, text_validation_type_or_show_slider_number=dump_text_validation_type_or_show_slider_number, text_validation_min=dump_text_validation_min, text_validation_max=dump_text_validation_max, identifier=dump_identifier, branching_logic=dump_branching_logic, required_field=dump_required_field, custom_alignment=dump_custom_alignment, question_number=dump_question_number, matrix_group_name=dump_matrix_group_name, matrix_ranking=dump_matrix_ranking, field_annotation=dump_field_annotation ) load_map = dict( field_name=load_field_name, form_name=load_form_name, section_header=load_section_header, field_type=load_field_type, field_label=load_field_label, select_choices_or_calculations=load_select_choices_or_calculations, field_note=load_field_note, text_validation_type_or_show_slider_number=load_text_validation_type_or_show_slider_number, text_validation_min=load_text_validation_min, text_validation_max=load_text_validation_max, identifier=load_identifier, branching_logic=load_branching_logic, required_field=load_required_field, custom_alignment=load_custom_alignment, question_number=load_question_number, matrix_group_name=load_matrix_group_name, matrix_ranking=load_matrix_ranking, field_annotation=load_field_annotation ) column_names = [ "field_name", "form_name", "section_header", "field_type", "field_label", "select_choices_or_calculations", "field_note", "text_validation_type_or_show_slider_number", "text_validation_min", "text_validation_max", "identifier", "branching_logic", "required_field", "custom_alignment", "question_number", "matrix_group_name", "matrix_ranking", "field_annotation", ] TemplateHTML = """ <!DOCTYPE html> <html> <head> </head> <body> <table id="metadata">{}</table> </body> </html> """.strip() class HTMLParser(HTMLParser): """extract metadata from HTML string""" pass class TemplateSQL: """statements for rendering SQL migration""" create_schema = "CREATE SCHEMA IF NOT EXISTS {};\n" create_table = "CREATE TABLE IF NOT EXISTS {}();\n" add_column = "ALTER TABLE {} ADD COLUMN IF NOT EXISTS {} {};\n" def nonce(length): """return pseudorandom string""" return "".join( choice(ascii_letters + digits) for _ in range(length) ) DCM = { # decimal context map "number": Context(prec=None, rounding=ROUND_HALF_UP), "number_1dp_comma_decimal": Context( prec=1, rounding=ROUND_HALF_UP ), "number_1dp": Context(prec=1, rounding=ROUND_HALF_UP), "number_2dp_comma_decimal": Context( prec=2, rounding=ROUND_HALF_UP ), "number_2dp": Context(prec=2, rounding=ROUND_HALF_UP), "number_3dp_comma_decimal": Context( prec=3, rounding=ROUND_HALF_UP ), "number_3dp": Context(prec=3, rounding=ROUND_HALF_UP), "number_4dp_comma_decimal": Context( prec=4, rounding=ROUND_HALF_UP ), "number_4dp": Context(prec=4, rounding=ROUND_HALF_UP), "number_comma_decimal": Context( prec=None, rounding=ROUND_HALF_UP ), } data_type_map = { "date_dmy": ( lambda d: date.strptime(d, "%d-%m-%Y"), lambda d: d.strftime("%d-%m-%Y"), "DATE", ), "date_mdy": ( lambda d: date.strptime(d, "%m-%d-%Y"), lambda d: d.strftime("%m-%d-%Y"), "DATE", ), "date_ymd": ( lambda d: date.strptime(d, "%Y-%m-%d"), lambda d: d.strftime("%Y-%m-%d"), "DATE", ), "datetime_dmy": ( lambda d: datetime.strptime(d, "%d-%m-%Y %H:%M"), lambda d: d.strftime("%d-%m-%Y %H:%M"), "DATETIME", ), "datetime_mdy": ( lambda d: datetime.strptime(d, "%m-%d-%Y %H:%M"), lambda d: d.strftime("%m-%d-%Y %H:%M"), "DATETIME", ), "datetime_ymd": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M"), lambda d: d.strftime("%Y-%m-%d %H:%M"), "DATETIME", ), "datetime_seconds_dmy": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M:%S"), lambda d: d.strftime("%Y-%m-%d %H:%M:%S"), "DATETIME", ), "datetime_seconds_mdy": ( lambda d: datetime.strptime(d, "%m-%d-%Y %H:%M:%S"), lambda d: d.strftime("%m-%d-%Y %H:%M:%S"), "DATETIME", ), "datetime_seconds_ymd": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M:%S"), lambda d: d.strftime("%Y-%m-%d %H:%M:%S"), "DATETIME", ), "email": (lambda s: s, lambda s: s, "TEXT",), "integer": (int, str, "INT",), "alpha_only": (lambda s: s, lambda s: s, "TEXT",), "number": ( lambda n: Decimal(sub(r",", ".", n), context=DCM["number"]), lambda n: str(n), "FLOAT", ), "number_1dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_1dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_1dp": ( lambda n: Decimal(n, context=DCM["number_1dp"]), lambda n: str(n), "FLOAT", ), "number_2dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_2dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_2dp": ( lambda n: Decimal(n, context=DCM["number_2dp"]), lambda n: str(n), "FLOAT", ), "number_3dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_3dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_3dp": ( lambda n: Decimal(n, context=DCM["number_3dp"]), lambda n: str(n), "FLOAT", ), "number_4dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_4dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_4dp": ( lambda n: Decimal(n, context=DCM["number_4dp"]), lambda n: str(n), "FLOAT", ), "number_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM["number_comma_decimal"] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "phone_australia": (lambda s: s, lambda s: s, "TEXT",), "phone": (lambda s: s, lambda s: s, "TEXT",), "postalcode_australia": (lambda s: s, lambda s: s, "TEXT",), "postalcode_canada": (lambda s: s, lambda s: s, "TEXT",), "ssn": (lambda s: s, lambda s: s, "TEXT",), "time": ( lambda t: time.strptime(t, "%H:%M"), lambda t: t.strftime("%H:%M"), "TIME", ), "time_mm_ss": ( lambda t: time.strptime(t, "%M:%S"), lambda t: t.strftime("%M:%S"), "TIME", ), "vmrn": (lambda s: s, lambda s: s, "TEXT",), "Zipcode": (lambda s: s, lambda s: s, "TEXT",), "": (lambda s: s, lambda s: s, "TEXT",), }
metadata/util.py
from collections import namedtuple from datetime import date, datetime, time from decimal import Context, Decimal, ROUND_HALF_UP from html.parser import HTMLParser from itertools import zip_longest from re import compile, finditer, sub from secrets import choice from string import ascii_letters, digits LOAD_VARIABLE_RE = compile(r"\[[\w()]+\]") LOAD_OPERATOR_RE = compile(r"(?<![<\|>]{1})=|<>") DUMP_VARIABLE_RE = compile(r"record\['\w+'\]") DUMP_OPERATOR_RE = compile(r"==|!=") def dump_field_name(value): """dump field_name""" return value def load_field_name(value): """load field_name""" return value def dump_form_name(value): """dump form_name""" return value def load_form_name(value): """load form_name""" return value def dump_section_header(value): """dump section_header""" return value def load_section_header(value): """load section_header""" return value def dump_field_type(value): """dump field_type""" return value def load_field_type(value): """load field_type""" return value def dump_field_label(value): """dump field_label""" return value def load_field_label(value): """load field_label""" return value def dump_select_choices_or_calculations(value): """dump select_choices_or_calculations""" return value def load_select_choices_or_calculations(value): """load select_choices_or_calculations""" return value def dump_field_note(value): """dump field_note""" return value def load_field_note(value): """load field_note""" return value def dump_text_validation_type_or_show_slider_number(value): """dump text_validation_type_or_show_slider_number""" return value def load_text_validation_type_or_show_slider_number(value): """load text_validation_type_or_show_slider_number""" return value def dump_text_validation_min(value): """dump text_validation_min""" return value def load_text_validation_min(value): """load text_validation_min""" return value def dump_text_validation_max(value): """dump text_validation_max""" return value def load_text_validation_max(value): """load text_validation_max""" return value def dump_identifier(value): """dump identifier""" if value is True: return "y" return "n" def load_identifier(value): """load identifier""" if value == "y": return True return False def dump_branching_logic(value): """dump branching_logic""" if not value: return "" logic_fragments = zip_longest( DUMP_VARIABLE_RE.split(value), [m.group(0) for m in DUMP_VARIABLE_RE.finditer(value)], fillvalue="" ) value = "" for oper_frag, vari_frag in logic_fragments: for match in DUMP_OPERATOR_RE.finditer(oper_frag): ope_str = match.group(0) if ope_str == "==": ope_str = "=" elif ope_str == "!=": ope_str = "<>" oper_frag = ( oper_frag[:match.start()] + ope_str + oper_frag[match.end():] ) if vari_frag: vari_frag = vari_frag.lstrip("record['").rstrip("']") if "___" in vari_frag: vari_frag = "(".join( s for s in vari_frag.split("___") ) + ")" vari_frag = "[" + vari_frag + "]" value += oper_frag + vari_frag return value def load_branching_logic(value): """load branching_logic""" if not value: return "" logic_fragments = zip_longest( LOAD_VARIABLE_RE.split(value), [m.group(0) for m in LOAD_VARIABLE_RE.finditer(value)], fillvalue="" ) value = "" for oper_frag, vari_frag in logic_fragments: for match in LOAD_OPERATOR_RE.finditer(oper_frag): ope_str = match.group(0) if ope_str == "=": ope_str = "==" elif ope_str == "<>": ope_str = "!=" oper_frag = ( oper_frag[:match.start()] + ope_str + oper_frag[match.end():] ) if vari_frag: vari_frag = vari_frag.strip("[]") if "(" in vari_frag and ")" in vari_frag: vari_frag = "___".join( s.strip(")") for s in vari_frag.split("(") ) vari_frag = "record['" + vari_frag + "']" value += oper_frag + vari_frag return value def dump_required_field(value): """dump required_field""" if value is True: return "y" return "n" def load_required_field(value): """load required_field""" if value == "y": return True return False def dump_custom_alignment(value): """dump custom_alignment""" return value def load_custom_alignment(value): """load custom_alignment""" return value def dump_question_number(value): """dump question_number""" return value def load_question_number(value): """load question_number""" return value def dump_matrix_group_name(value): """dump matrix_group_name""" return value def load_matrix_group_name(value): """load matrix_group_name""" return value def dump_matrix_ranking(value): """dump matrix_ranking""" return value def load_matrix_ranking(value): """load matrix_ranking""" return value def dump_field_annotation(value): """dump field_annotation""" return value def load_field_annotation(value): """load field_annotation""" return value dump_map = dict( field_name=dump_field_name, form_name=dump_form_name, section_header=dump_section_header, field_type=dump_field_type, field_label=dump_field_label, select_choices_or_calculations=dump_select_choices_or_calculations, field_note=dump_field_note, text_validation_type_or_show_slider_number=dump_text_validation_type_or_show_slider_number, text_validation_min=dump_text_validation_min, text_validation_max=dump_text_validation_max, identifier=dump_identifier, branching_logic=dump_branching_logic, required_field=dump_required_field, custom_alignment=dump_custom_alignment, question_number=dump_question_number, matrix_group_name=dump_matrix_group_name, matrix_ranking=dump_matrix_ranking, field_annotation=dump_field_annotation ) load_map = dict( field_name=load_field_name, form_name=load_form_name, section_header=load_section_header, field_type=load_field_type, field_label=load_field_label, select_choices_or_calculations=load_select_choices_or_calculations, field_note=load_field_note, text_validation_type_or_show_slider_number=load_text_validation_type_or_show_slider_number, text_validation_min=load_text_validation_min, text_validation_max=load_text_validation_max, identifier=load_identifier, branching_logic=load_branching_logic, required_field=load_required_field, custom_alignment=load_custom_alignment, question_number=load_question_number, matrix_group_name=load_matrix_group_name, matrix_ranking=load_matrix_ranking, field_annotation=load_field_annotation ) column_names = [ "field_name", "form_name", "section_header", "field_type", "field_label", "select_choices_or_calculations", "field_note", "text_validation_type_or_show_slider_number", "text_validation_min", "text_validation_max", "identifier", "branching_logic", "required_field", "custom_alignment", "question_number", "matrix_group_name", "matrix_ranking", "field_annotation", ] TemplateHTML = """ <!DOCTYPE html> <html> <head> </head> <body> <table id="metadata">{}</table> </body> </html> """.strip() class HTMLParser(HTMLParser): """extract metadata from HTML string""" pass class TemplateSQL: """statements for rendering SQL migration""" create_schema = "CREATE SCHEMA IF NOT EXISTS {};\n" create_table = "CREATE TABLE IF NOT EXISTS {}();\n" add_column = "ALTER TABLE {} ADD COLUMN IF NOT EXISTS {} {};\n" def nonce(length): """return pseudorandom string""" return "".join( choice(ascii_letters + digits) for _ in range(length) ) DCM = { # decimal context map "number": Context(prec=None, rounding=ROUND_HALF_UP), "number_1dp_comma_decimal": Context( prec=1, rounding=ROUND_HALF_UP ), "number_1dp": Context(prec=1, rounding=ROUND_HALF_UP), "number_2dp_comma_decimal": Context( prec=2, rounding=ROUND_HALF_UP ), "number_2dp": Context(prec=2, rounding=ROUND_HALF_UP), "number_3dp_comma_decimal": Context( prec=3, rounding=ROUND_HALF_UP ), "number_3dp": Context(prec=3, rounding=ROUND_HALF_UP), "number_4dp_comma_decimal": Context( prec=4, rounding=ROUND_HALF_UP ), "number_4dp": Context(prec=4, rounding=ROUND_HALF_UP), "number_comma_decimal": Context( prec=None, rounding=ROUND_HALF_UP ), } data_type_map = { "date_dmy": ( lambda d: date.strptime(d, "%d-%m-%Y"), lambda d: d.strftime("%d-%m-%Y"), "DATE", ), "date_mdy": ( lambda d: date.strptime(d, "%m-%d-%Y"), lambda d: d.strftime("%m-%d-%Y"), "DATE", ), "date_ymd": ( lambda d: date.strptime(d, "%Y-%m-%d"), lambda d: d.strftime("%Y-%m-%d"), "DATE", ), "datetime_dmy": ( lambda d: datetime.strptime(d, "%d-%m-%Y %H:%M"), lambda d: d.strftime("%d-%m-%Y %H:%M"), "DATETIME", ), "datetime_mdy": ( lambda d: datetime.strptime(d, "%m-%d-%Y %H:%M"), lambda d: d.strftime("%m-%d-%Y %H:%M"), "DATETIME", ), "datetime_ymd": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M"), lambda d: d.strftime("%Y-%m-%d %H:%M"), "DATETIME", ), "datetime_seconds_dmy": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M:%S"), lambda d: d.strftime("%Y-%m-%d %H:%M:%S"), "DATETIME", ), "datetime_seconds_mdy": ( lambda d: datetime.strptime(d, "%m-%d-%Y %H:%M:%S"), lambda d: d.strftime("%m-%d-%Y %H:%M:%S"), "DATETIME", ), "datetime_seconds_ymd": ( lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M:%S"), lambda d: d.strftime("%Y-%m-%d %H:%M:%S"), "DATETIME", ), "email": (lambda s: s, lambda s: s, "TEXT",), "integer": (int, str, "INT",), "alpha_only": (lambda s: s, lambda s: s, "TEXT",), "number": ( lambda n: Decimal(sub(r",", ".", n), context=DCM["number"]), lambda n: str(n), "FLOAT", ), "number_1dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_1dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_1dp": ( lambda n: Decimal(n, context=DCM["number_1dp"]), lambda n: str(n), "FLOAT", ), "number_2dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_2dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_2dp": ( lambda n: Decimal(n, context=DCM["number_2dp"]), lambda n: str(n), "FLOAT", ), "number_3dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_3dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_3dp": ( lambda n: Decimal(n, context=DCM["number_3dp"]), lambda n: str(n), "FLOAT", ), "number_4dp_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM[ "number_4dp_comma_decimal" ] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "number_4dp": ( lambda n: Decimal(n, context=DCM["number_4dp"]), lambda n: str(n), "FLOAT", ), "number_comma_decimal": ( lambda n: Decimal( sub(r",", ".", n), context=DCM["number_comma_decimal"] ), lambda n: sub(r"\.", ",", str(n)), "FLOAT", ), "phone_australia": (lambda s: s, lambda s: s, "TEXT",), "phone": (lambda s: s, lambda s: s, "TEXT",), "postalcode_australia": (lambda s: s, lambda s: s, "TEXT",), "postalcode_canada": (lambda s: s, lambda s: s, "TEXT",), "ssn": (lambda s: s, lambda s: s, "TEXT",), "time": ( lambda t: time.strptime(t, "%H:%M"), lambda t: t.strftime("%H:%M"), "TIME", ), "time_mm_ss": ( lambda t: time.strptime(t, "%M:%S"), lambda t: t.strftime("%M:%S"), "TIME", ), "vmrn": (lambda s: s, lambda s: s, "TEXT",), "Zipcode": (lambda s: s, lambda s: s, "TEXT",), "": (lambda s: s, lambda s: s, "TEXT",), }
0.643329
0.190686
import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True) def normalize(input_image, input_mask): input_image = tf.cast(input_image, tf.float32) / 255.0 input_mask -= 1 return input_image, input_mask @tf.function def load_image_train(datapoint): input_image = tf.image.resize(datapoint['image'], (128, 128)) input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128)) if tf.random.uniform(()) > 0.5: input_image = tf.image.flip_left_right(input_image) input_mask = tf.image.flip_left_right(input_mask) input_image, input_mask = normalize(input_image, input_mask) return input_image, input_mask def load_image_test(datapoint): input_image = tf.image.resize(datapoint['image'], (128, 128)) input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128)) input_image, input_mask = normalize(input_image, input_mask) return input_image, input_mask TRAIN_LENGTH = info.splits['train'].num_examples BATCH_SIZE = 64 BUFFER_SIZE = 1000 STEPS_PER_EPOCH = TRAIN_LENGTH // BATCH_SIZE train = dataset['train'].map(load_image_train, num_parallel_calls=tf.data.AUTOTUNE) test = dataset['test'].map(load_image_test) train_dataset = train.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat() train_dataset = train_dataset.prefetch(buffer_size=tf.data.AUTOTUNE) test_dataset = test.batch(BATCH_SIZE) def display(display_list): plt.figure(figsize=(15, 15)) title = ['Input Image', 'True Mask', 'Predicted Mask'] for i in range(len(display_list)): plt.subplot(1, len(display_list), i + 1) plt.title(title[i]) plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i])) plt.axis('off') def upsample(filters, size): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) result.add(tf.keras.layers.BatchNormalization()) result.add(tf.keras.layers.ReLU()) return result for image, mask in train.take(1): sample_image, sample_mask = image, mask display([sample_image, sample_mask]) OUTPUT_CHANNELS = 3 base_model = tf.keras.applications.MobileNetV2(input_shape=[128, 128, 3], include_top=False) # Use the activations of these layers layer_names = [ 'block_1_expand_relu', # 64x64 'block_3_expand_relu', # 32x32 'block_6_expand_relu', # 16x16 'block_13_expand_relu', # 8x8 'block_16_project', # 4x4 ] layers = [base_model.get_layer(name).output for name in layer_names] # Create the feature extraction model down_stack = tf.keras.Model(inputs=base_model.input, outputs=layers) down_stack.trainable = False up_stack = [ upsample(512, 3), # 4x4 -> 8x8 upsample(256, 3), # 8x8 -> 16x16 upsample(128, 3), # 16x16 -> 32x32 upsample(64, 3), # 32x32 -> 64x64 ] def unet_model(output_channels): inputs = tf.keras.layers.Input(shape=[128, 128, 3]) x = inputs # Downsampling through the model skips = down_stack(x) x = skips[-1] skips = reversed(skips[:-1]) # Upsampling and establishing the skip connections for up, skip in zip(up_stack, skips): x = up(x) concat = tf.keras.layers.Concatenate() x = concat([x, skip]) # This is the last layer of the model last = tf.keras.layers.Conv2DTranspose(output_channels, 3, strides=2, padding='same') # 64x64 -> 128x128 x = last(x) return tf.keras.Model(inputs=inputs, outputs=x) model = unet_model(OUTPUT_CHANNELS) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) def create_mask(pred_mask): pred_mask = tf.argmax(pred_mask, axis=-1) pred_mask = pred_mask[..., tf.newaxis] return pred_mask[0] def show_predictions(dataset=None, num=1): if dataset: for image, mask in dataset.take(num): pred_mask = model.predict(image) display([image[0], mask[0], create_mask(pred_mask)]) else: display([sample_image, sample_mask, create_mask(model.predict(sample_image[tf.newaxis, ...]))]) show_predictions() EPOCHS = 20 VAL_SUB_SPLITS = 5 VALIDATION_STEPS = info.splits['test'].num_examples // BATCH_SIZE // VAL_SUB_SPLITS model.fit(train_dataset, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH, validation_steps=VALIDATION_STEPS, validation_data=test_dataset) show_predictions(test_dataset, 3) plt.show()
unet.py
import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True) def normalize(input_image, input_mask): input_image = tf.cast(input_image, tf.float32) / 255.0 input_mask -= 1 return input_image, input_mask @tf.function def load_image_train(datapoint): input_image = tf.image.resize(datapoint['image'], (128, 128)) input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128)) if tf.random.uniform(()) > 0.5: input_image = tf.image.flip_left_right(input_image) input_mask = tf.image.flip_left_right(input_mask) input_image, input_mask = normalize(input_image, input_mask) return input_image, input_mask def load_image_test(datapoint): input_image = tf.image.resize(datapoint['image'], (128, 128)) input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128)) input_image, input_mask = normalize(input_image, input_mask) return input_image, input_mask TRAIN_LENGTH = info.splits['train'].num_examples BATCH_SIZE = 64 BUFFER_SIZE = 1000 STEPS_PER_EPOCH = TRAIN_LENGTH // BATCH_SIZE train = dataset['train'].map(load_image_train, num_parallel_calls=tf.data.AUTOTUNE) test = dataset['test'].map(load_image_test) train_dataset = train.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat() train_dataset = train_dataset.prefetch(buffer_size=tf.data.AUTOTUNE) test_dataset = test.batch(BATCH_SIZE) def display(display_list): plt.figure(figsize=(15, 15)) title = ['Input Image', 'True Mask', 'Predicted Mask'] for i in range(len(display_list)): plt.subplot(1, len(display_list), i + 1) plt.title(title[i]) plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i])) plt.axis('off') def upsample(filters, size): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) result.add(tf.keras.layers.BatchNormalization()) result.add(tf.keras.layers.ReLU()) return result for image, mask in train.take(1): sample_image, sample_mask = image, mask display([sample_image, sample_mask]) OUTPUT_CHANNELS = 3 base_model = tf.keras.applications.MobileNetV2(input_shape=[128, 128, 3], include_top=False) # Use the activations of these layers layer_names = [ 'block_1_expand_relu', # 64x64 'block_3_expand_relu', # 32x32 'block_6_expand_relu', # 16x16 'block_13_expand_relu', # 8x8 'block_16_project', # 4x4 ] layers = [base_model.get_layer(name).output for name in layer_names] # Create the feature extraction model down_stack = tf.keras.Model(inputs=base_model.input, outputs=layers) down_stack.trainable = False up_stack = [ upsample(512, 3), # 4x4 -> 8x8 upsample(256, 3), # 8x8 -> 16x16 upsample(128, 3), # 16x16 -> 32x32 upsample(64, 3), # 32x32 -> 64x64 ] def unet_model(output_channels): inputs = tf.keras.layers.Input(shape=[128, 128, 3]) x = inputs # Downsampling through the model skips = down_stack(x) x = skips[-1] skips = reversed(skips[:-1]) # Upsampling and establishing the skip connections for up, skip in zip(up_stack, skips): x = up(x) concat = tf.keras.layers.Concatenate() x = concat([x, skip]) # This is the last layer of the model last = tf.keras.layers.Conv2DTranspose(output_channels, 3, strides=2, padding='same') # 64x64 -> 128x128 x = last(x) return tf.keras.Model(inputs=inputs, outputs=x) model = unet_model(OUTPUT_CHANNELS) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) def create_mask(pred_mask): pred_mask = tf.argmax(pred_mask, axis=-1) pred_mask = pred_mask[..., tf.newaxis] return pred_mask[0] def show_predictions(dataset=None, num=1): if dataset: for image, mask in dataset.take(num): pred_mask = model.predict(image) display([image[0], mask[0], create_mask(pred_mask)]) else: display([sample_image, sample_mask, create_mask(model.predict(sample_image[tf.newaxis, ...]))]) show_predictions() EPOCHS = 20 VAL_SUB_SPLITS = 5 VALIDATION_STEPS = info.splits['test'].num_examples // BATCH_SIZE // VAL_SUB_SPLITS model.fit(train_dataset, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH, validation_steps=VALIDATION_STEPS, validation_data=test_dataset) show_predictions(test_dataset, 3) plt.show()
0.858526
0.693022
import requests import os from people_detection import PeopleDetection from PIL import Image from io import BytesIO from time import time, sleep class Scam(object): base_url = "http://scam.42.fr" cam_endpoints = { # region: [camera, camera, camera] "e0": [ "cam-e1-sm-rue", "cam-e1-sm-resto", "cam-e0-petit-couloir", ], "e1": [ "cam-e1-hall-porte", "cam-e1-sm-so", "cam-e1-sm-se", "cam-e1-sm-ne", "cam-e1-sm-no", ], "e2": [ "cam-e2-playstation", "cam-e2-detente-sud", "cam-e2-detente-ouest", "cam-e2-detente-est", "cam-e2-sm-porte", "cam-e2-sm-so", "cam-e2-sm-se", "cam-e2-sm-ne", "cam-e2-sm-no", ], "e3": [ "cam-e3-sm-porte", "cam-e3-sm-so", "cam-e3-sm-se", "cam-e3-sm-ne", "cam-e3-sm-no", ], "amphi": [ "cam-e0-amphi-rue", "cam-e0-amphi-resto", ], "bocal": [ "cam-e3-bocal-out", ], "kfet": [ "cam-ext-rie-nord", "cam-ext-rie-sud", "cam-kfet-cuisine-no", "cam-kfet-cuisine-se", "cam-kfet-bar-no", "cam-kfet-bar-se", "cam-kfet-resto-ne", "cam-kfet-resto-so", ], "cloture": [ "cam-ext-moto", "cam-ext-moto2", "cam-ext-angle-r-sud", "cam-ext-angle-b-est", "cam-ext-portillon-nord", "cam-ext-portillon-sud", "cam-ext-sas-nord", "cam-ext-sas-sud", "cam-ext-rie-nord", ], } scam_endpoint = "/cams/%s.jpg" class CamDoesNotExist(Exception): """Only purpose of this exception is to give a clear message error for debug.""" def __init__(self, region, camera): super(CamDoesNotExist, self).__init__("Error camera: %s (%s) does not exist." % (camera, region)) def __init__(self, camera): """Return the Scam object for the camera.""" self.region = self._get_camera_region(camera) self.camera = camera self.dir_path = "img/%s/%s" % (self.region, self.camera) self.pd = PeopleDetection(self._get_background_img_path()) def _get_camera_region(self, camera): """Get the region of the camera. Return the region if camera is found. Else raise CamDoesNotExist exception.""" for cam_region, cam_list in self.cam_endpoints.items(): if camera in cam_list: return cam_region raise self.CamDoesNotExist("???", camera) def _get_cam_data(self, camera): """ Perform an GET request to scam and return the camera image as binary content if success. If request fail, return None. """ nowstamp = int(time()) try: rep = requests.get("%s%s?%s" % (self.base_url, (self.scam_endpoint % camera), nowstamp)) if rep.ok: return rep.content except requests.exceptions.RequestException as e: print("Error with request: %s" % e) return None def _get_background_mask_path(self): """Try to get the background mask image. Return the path if exist, else return None""" if os.path.isfile("%s/mask.jpg" % (self.dir_path)): return "%s/mask.jpg" % self.dir_path else: return None def _get_background_img_path(self): """Try to get the background image. Return the path if exist, else return None""" if os.path.isfile("%s/background.jpg" % (self.dir_path)): return "%s/background.jpg" % (self.dir_path) else: return None @staticmethod def _get_and_crop_data_to_image(data): """Take Cam binary data and crop it to remove Date/Hour. Then return an Pillow Image object.""" img = Image.open(BytesIO(data)) w, h = img.size try: img.crop((0, 35, w, (h - 35))) except OSError: # Every image from scam always raise an 'image file is truncated' error. # This first try catch this weird error. TODO (do it properly !) pass return img.crop((0, 35, w, (h - 35))) def get_cam_image(self): """Return Image object of the camera current image. Else return None""" data = self._get_cam_data(self.camera) if data: return self._get_and_crop_data_to_image(data) else: return None def save_cam_image(self, filename="1.jpg"): """ Save the desired self.camera into the img path: img/{self.region}/{self.camera}/{filename}. Return Image object of the current image on camera. """ os.makedirs(self.dir_path, exist_ok=True) img = self.get_cam_image() img.save("%s/%s" % (self.dir_path, filename), "JPEG") return img
scam.py
import requests import os from people_detection import PeopleDetection from PIL import Image from io import BytesIO from time import time, sleep class Scam(object): base_url = "http://scam.42.fr" cam_endpoints = { # region: [camera, camera, camera] "e0": [ "cam-e1-sm-rue", "cam-e1-sm-resto", "cam-e0-petit-couloir", ], "e1": [ "cam-e1-hall-porte", "cam-e1-sm-so", "cam-e1-sm-se", "cam-e1-sm-ne", "cam-e1-sm-no", ], "e2": [ "cam-e2-playstation", "cam-e2-detente-sud", "cam-e2-detente-ouest", "cam-e2-detente-est", "cam-e2-sm-porte", "cam-e2-sm-so", "cam-e2-sm-se", "cam-e2-sm-ne", "cam-e2-sm-no", ], "e3": [ "cam-e3-sm-porte", "cam-e3-sm-so", "cam-e3-sm-se", "cam-e3-sm-ne", "cam-e3-sm-no", ], "amphi": [ "cam-e0-amphi-rue", "cam-e0-amphi-resto", ], "bocal": [ "cam-e3-bocal-out", ], "kfet": [ "cam-ext-rie-nord", "cam-ext-rie-sud", "cam-kfet-cuisine-no", "cam-kfet-cuisine-se", "cam-kfet-bar-no", "cam-kfet-bar-se", "cam-kfet-resto-ne", "cam-kfet-resto-so", ], "cloture": [ "cam-ext-moto", "cam-ext-moto2", "cam-ext-angle-r-sud", "cam-ext-angle-b-est", "cam-ext-portillon-nord", "cam-ext-portillon-sud", "cam-ext-sas-nord", "cam-ext-sas-sud", "cam-ext-rie-nord", ], } scam_endpoint = "/cams/%s.jpg" class CamDoesNotExist(Exception): """Only purpose of this exception is to give a clear message error for debug.""" def __init__(self, region, camera): super(CamDoesNotExist, self).__init__("Error camera: %s (%s) does not exist." % (camera, region)) def __init__(self, camera): """Return the Scam object for the camera.""" self.region = self._get_camera_region(camera) self.camera = camera self.dir_path = "img/%s/%s" % (self.region, self.camera) self.pd = PeopleDetection(self._get_background_img_path()) def _get_camera_region(self, camera): """Get the region of the camera. Return the region if camera is found. Else raise CamDoesNotExist exception.""" for cam_region, cam_list in self.cam_endpoints.items(): if camera in cam_list: return cam_region raise self.CamDoesNotExist("???", camera) def _get_cam_data(self, camera): """ Perform an GET request to scam and return the camera image as binary content if success. If request fail, return None. """ nowstamp = int(time()) try: rep = requests.get("%s%s?%s" % (self.base_url, (self.scam_endpoint % camera), nowstamp)) if rep.ok: return rep.content except requests.exceptions.RequestException as e: print("Error with request: %s" % e) return None def _get_background_mask_path(self): """Try to get the background mask image. Return the path if exist, else return None""" if os.path.isfile("%s/mask.jpg" % (self.dir_path)): return "%s/mask.jpg" % self.dir_path else: return None def _get_background_img_path(self): """Try to get the background image. Return the path if exist, else return None""" if os.path.isfile("%s/background.jpg" % (self.dir_path)): return "%s/background.jpg" % (self.dir_path) else: return None @staticmethod def _get_and_crop_data_to_image(data): """Take Cam binary data and crop it to remove Date/Hour. Then return an Pillow Image object.""" img = Image.open(BytesIO(data)) w, h = img.size try: img.crop((0, 35, w, (h - 35))) except OSError: # Every image from scam always raise an 'image file is truncated' error. # This first try catch this weird error. TODO (do it properly !) pass return img.crop((0, 35, w, (h - 35))) def get_cam_image(self): """Return Image object of the camera current image. Else return None""" data = self._get_cam_data(self.camera) if data: return self._get_and_crop_data_to_image(data) else: return None def save_cam_image(self, filename="1.jpg"): """ Save the desired self.camera into the img path: img/{self.region}/{self.camera}/{filename}. Return Image object of the current image on camera. """ os.makedirs(self.dir_path, exist_ok=True) img = self.get_cam_image() img.save("%s/%s" % (self.dir_path, filename), "JPEG") return img
0.583915
0.230259
import unittest from envdiff.diff import Diff class TestDiff(unittest.TestCase): def test_loads_files_on_construction(self): expected_contents = ['URL=https://www.test.com/', 'FOO=BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') self.assertEqual(self.differ.left, expected_contents) self.assertEqual(self.differ.right, expected_contents) def test_convert_to_dict(self): contents = ['FOO=BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.convert_to_dict(contents, '=') self.assertEqual(result, { 'FOO': 'BAR' }) def test_convert_to_dict_with_alternate_separator(self): contents = ['FOO: BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.convert_to_dict(contents, ': ') self.assertEqual(result, { 'FOO': 'BAR' }) def test_find_unique_keys(self): left = { 'FOO': 'BAR', 'LEFT': 'parsnip' } right = { 'FOO': 'BAR', 'RIGHT': 'persimmon' } expected = { 'left': ['LEFT'], 'right': ['RIGHT'] } self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.find_unique_keys(left, right) self.assertEqual(result, expected) def test_find_distinct_shared_keys(self): left = { 'FOO': 'BAR', 'LEFT': 'parsnip' } right = { 'FOO': 'BOO', 'RIGHT': 'persimmon' } expected = [ 'FOO' ] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.find_distinct_shared_keys(left, right) self.assertEqual(result, expected) def test_files_are_indentical(self): left = { 'FOO': 'BAR' } right = { 'FOO': 'BAR' } self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') self.assertEqual(self.differ.find_unique_keys(left, right), { 'left': [], 'right': [] }) self.assertEqual(self.differ.find_distinct_shared_keys(left, right), []) def test_diff_with_indentical_files(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, {}) self.assertEqual(unique_list, { 'left': {}, 'right': {} }) def test_diff_with_files_with_shared_keys_that_differ(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-shared') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'left': 'BAR', 'right': 'FOO' } }) def test_diff_with_files_with_unique_keys(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-unique') shared_list, unique_list = self.differ.diff() self.assertEqual(unique_list, { 'left': { 'FOO': 'BAR' }, 'right': { 'BAR': 'FOO' } }) def test_diff_with_files_with_unique_and_shared_keys(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-shared-and-unique') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'left': 'BAR', 'right': 'FOO' } }) self.assertEqual(unique_list, { 'left': { 'URL': 'https://www.test.com/' }, 'right': { 'BAR': 'FOO' } }) def test_diff_loading_files_in_opposite_order(self): self.differ = Diff('test/fixtures/.env-simple-shared-and-unique', 'test/fixtures/.env-simple') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'right': 'BAR', 'left': 'FOO' } }) self.assertEqual(unique_list, { 'right': { 'URL': 'https://www.test.com/' }, 'left': { 'BAR': 'FOO' } }) def tearDown(self): self.differ = None if __name__ == '__main__': unittest.main()
test/test_diff.py
import unittest from envdiff.diff import Diff class TestDiff(unittest.TestCase): def test_loads_files_on_construction(self): expected_contents = ['URL=https://www.test.com/', 'FOO=BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') self.assertEqual(self.differ.left, expected_contents) self.assertEqual(self.differ.right, expected_contents) def test_convert_to_dict(self): contents = ['FOO=BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.convert_to_dict(contents, '=') self.assertEqual(result, { 'FOO': 'BAR' }) def test_convert_to_dict_with_alternate_separator(self): contents = ['FOO: BAR'] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.convert_to_dict(contents, ': ') self.assertEqual(result, { 'FOO': 'BAR' }) def test_find_unique_keys(self): left = { 'FOO': 'BAR', 'LEFT': 'parsnip' } right = { 'FOO': 'BAR', 'RIGHT': 'persimmon' } expected = { 'left': ['LEFT'], 'right': ['RIGHT'] } self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.find_unique_keys(left, right) self.assertEqual(result, expected) def test_find_distinct_shared_keys(self): left = { 'FOO': 'BAR', 'LEFT': 'parsnip' } right = { 'FOO': 'BOO', 'RIGHT': 'persimmon' } expected = [ 'FOO' ] self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') result = self.differ.find_distinct_shared_keys(left, right) self.assertEqual(result, expected) def test_files_are_indentical(self): left = { 'FOO': 'BAR' } right = { 'FOO': 'BAR' } self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') self.assertEqual(self.differ.find_unique_keys(left, right), { 'left': [], 'right': [] }) self.assertEqual(self.differ.find_distinct_shared_keys(left, right), []) def test_diff_with_indentical_files(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, {}) self.assertEqual(unique_list, { 'left': {}, 'right': {} }) def test_diff_with_files_with_shared_keys_that_differ(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-shared') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'left': 'BAR', 'right': 'FOO' } }) def test_diff_with_files_with_unique_keys(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-unique') shared_list, unique_list = self.differ.diff() self.assertEqual(unique_list, { 'left': { 'FOO': 'BAR' }, 'right': { 'BAR': 'FOO' } }) def test_diff_with_files_with_unique_and_shared_keys(self): self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple-shared-and-unique') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'left': 'BAR', 'right': 'FOO' } }) self.assertEqual(unique_list, { 'left': { 'URL': 'https://www.test.com/' }, 'right': { 'BAR': 'FOO' } }) def test_diff_loading_files_in_opposite_order(self): self.differ = Diff('test/fixtures/.env-simple-shared-and-unique', 'test/fixtures/.env-simple') shared_list, unique_list = self.differ.diff() self.assertEqual(shared_list, { 'FOO': { 'right': 'BAR', 'left': 'FOO' } }) self.assertEqual(unique_list, { 'right': { 'URL': 'https://www.test.com/' }, 'left': { 'BAR': 'FOO' } }) def tearDown(self): self.differ = None if __name__ == '__main__': unittest.main()
0.608478
0.661718
from datetime import ( date, datetime, time, timedelta ) from babel.dates import ( format_date, format_datetime, format_time, format_timedelta, get_timezone ) from pyramid.compat import text_type def date_formatter(request, value, format='medium', locale_name=None): """Date formatter """ if not isinstance(value, datetime) and not isinstance(value, date): return value if not locale_name: locale_name = request.locale_name return text_type(format_date(value, format, locale_name)) def time_formatter(request, value, format='medium', tzname=None, locale_name=None): """Time formatters """ if not isinstance(value, datetime) and not isinstance(value, time): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['pyramid.default_timezone_name']) if not locale_name: locale_name = request.locale_name return text_type(format_time(value, format, tzinfo, locale_name)) def datetime_formatter(request, value, format='medium', tzname=None, locale_name=None): """DateTime formatter Short:: >> dt = datetime(2011, 2, 6, 10, 35, 45, 80, pytz.UTC) >> request.format.datetime(dt, 'short') '02/06/11 04:35 AM' Medium:: >> request.format.datetime(dt, 'medium') 'Feb 06, 2011 04:35 AM' Long:: >> request.format.datetime(dt, 'long') 'February 06, 2011 04:35 AM -0600' Full:: >> request.format.datetime(dt, 'full') 'Sunday, February 06, 2011 04:35:45 AM CST' """ if not isinstance(value, datetime): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['pyramid.default_timezone_name']) if not locale_name: locale_name = request.locale_name return text_type(format_datetime(value, format, tzinfo, locale_name)) def timedelta_formatter(request, value, granularity='second', threshold=.85, add_direction=False, format='medium', locale_name=None): """Timedelta formatter Format:: >> td = timedelta(hours=10, minutes=5, seconds=45) >> request.format.timedelta(td, format='medium') '10 hours' >> request.format.timedelta(td, format='short') '10 hrs' Default:: >> request.format.timedelta(td) '10 hours' """ if not isinstance(value, timedelta): return value if not locale_name: locale_name = request.locale_name return text_type(format_timedelta( value, format=format, granularity=granularity, threshold=threshold, add_direction=add_direction, locale=locale_name))
djed/formatter/datetime.py
from datetime import ( date, datetime, time, timedelta ) from babel.dates import ( format_date, format_datetime, format_time, format_timedelta, get_timezone ) from pyramid.compat import text_type def date_formatter(request, value, format='medium', locale_name=None): """Date formatter """ if not isinstance(value, datetime) and not isinstance(value, date): return value if not locale_name: locale_name = request.locale_name return text_type(format_date(value, format, locale_name)) def time_formatter(request, value, format='medium', tzname=None, locale_name=None): """Time formatters """ if not isinstance(value, datetime) and not isinstance(value, time): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['pyramid.default_timezone_name']) if not locale_name: locale_name = request.locale_name return text_type(format_time(value, format, tzinfo, locale_name)) def datetime_formatter(request, value, format='medium', tzname=None, locale_name=None): """DateTime formatter Short:: >> dt = datetime(2011, 2, 6, 10, 35, 45, 80, pytz.UTC) >> request.format.datetime(dt, 'short') '02/06/11 04:35 AM' Medium:: >> request.format.datetime(dt, 'medium') 'Feb 06, 2011 04:35 AM' Long:: >> request.format.datetime(dt, 'long') 'February 06, 2011 04:35 AM -0600' Full:: >> request.format.datetime(dt, 'full') 'Sunday, February 06, 2011 04:35:45 AM CST' """ if not isinstance(value, datetime): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['pyramid.default_timezone_name']) if not locale_name: locale_name = request.locale_name return text_type(format_datetime(value, format, tzinfo, locale_name)) def timedelta_formatter(request, value, granularity='second', threshold=.85, add_direction=False, format='medium', locale_name=None): """Timedelta formatter Format:: >> td = timedelta(hours=10, minutes=5, seconds=45) >> request.format.timedelta(td, format='medium') '10 hours' >> request.format.timedelta(td, format='short') '10 hrs' Default:: >> request.format.timedelta(td) '10 hours' """ if not isinstance(value, timedelta): return value if not locale_name: locale_name = request.locale_name return text_type(format_timedelta( value, format=format, granularity=granularity, threshold=threshold, add_direction=add_direction, locale=locale_name))
0.605449
0.127979
import socket import sys import signal import time BUFFER_SIZE = 1024 def recv(sock): buffer = sock.recv(BUFFER_SIZE) out = buffer.decode('utf-8') if out != "ok": raise "Failed to receive a message" print("receiving: " + out) def sendto(sock, remote, cmd): print("cmd: " + cmd) sock.sendto(cmd.encode('utf-8'), remote) if __name__ == '__main__': print("commanding...") local = ('', 8889) remote = ('192.168.10.1', 8889) signal.signal(signal.SIGINT, signal.SIG_DFL) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(local) sock.setblocking(False) try: print("Attempting to connect with drone..") attempts = 3 ack = False for i in range(attempts): try: print("Attempt number is " + str(i)) sock.sendto('command'.encode('utf-8'), remote) buffer = sock.recv(BUFFER_SIZE) out = buffer.decode('utf-8') if out == 'ok': print('accepted') ack = True break else: print('rejected') time.sleep(0.5) except Exception as e: print("Failed to connect. Retrying...") time.sleep(0.5) pass if not ack: raise Exception("Failed to connect. Stop trying.") sock.setblocking(True) # commands sendto(sock, remote, "takeoff") recv(sock) time.sleep(3.5) sendto(sock, remote, "rc 0 0 0 30") recv(sock) time.sleep(7.5) sendto(sock, remote, "rc 0 0 0 -30") recv(sock) time.sleep(7.5) # sendto(sock, remote, "rc 0 0 5 0") # recv(sock) # time.sleep(3.5) # sendto(sock, remote, "rc 0 0 -15 0") # recv(sock) # time.sleep(3.5) sendto(sock, remote, "land") recv(sock) time.sleep(3.5) except Exception as e: sendto(sock, remote, "land") print("Exception in run():" + str(e)) finally: sock.close() print("closing the socket")
command_drone.py
import socket import sys import signal import time BUFFER_SIZE = 1024 def recv(sock): buffer = sock.recv(BUFFER_SIZE) out = buffer.decode('utf-8') if out != "ok": raise "Failed to receive a message" print("receiving: " + out) def sendto(sock, remote, cmd): print("cmd: " + cmd) sock.sendto(cmd.encode('utf-8'), remote) if __name__ == '__main__': print("commanding...") local = ('', 8889) remote = ('192.168.10.1', 8889) signal.signal(signal.SIGINT, signal.SIG_DFL) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(local) sock.setblocking(False) try: print("Attempting to connect with drone..") attempts = 3 ack = False for i in range(attempts): try: print("Attempt number is " + str(i)) sock.sendto('command'.encode('utf-8'), remote) buffer = sock.recv(BUFFER_SIZE) out = buffer.decode('utf-8') if out == 'ok': print('accepted') ack = True break else: print('rejected') time.sleep(0.5) except Exception as e: print("Failed to connect. Retrying...") time.sleep(0.5) pass if not ack: raise Exception("Failed to connect. Stop trying.") sock.setblocking(True) # commands sendto(sock, remote, "takeoff") recv(sock) time.sleep(3.5) sendto(sock, remote, "rc 0 0 0 30") recv(sock) time.sleep(7.5) sendto(sock, remote, "rc 0 0 0 -30") recv(sock) time.sleep(7.5) # sendto(sock, remote, "rc 0 0 5 0") # recv(sock) # time.sleep(3.5) # sendto(sock, remote, "rc 0 0 -15 0") # recv(sock) # time.sleep(3.5) sendto(sock, remote, "land") recv(sock) time.sleep(3.5) except Exception as e: sendto(sock, remote, "land") print("Exception in run():" + str(e)) finally: sock.close() print("closing the socket")
0.123617
0.064506
import os import time import fnmatch def match(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, verbose=False): ''' :param paths: path for clean :param atimeout: file will be deleted after access timeout :param ctimeout: file will be deleted after creation timeout :param mtimeout: file will be deleted after modification timeout :param seed: base line of current time :param patterns: includes and excludes patterns with format [('i', pattern), ('e', pattern), ...] :return: file list ''' # args check if isinstance(paths, str): paths = [paths] assert isinstance(paths, (tuple, list)) if seed is None: seed = time.time() if patterns is None: patterns = ['i', '*'] # match function def check_include(f): # check patterns for t, p in patterns: m = fnmatch.fnmatch(file_path, p) if t == 'i': if not m: continue break else: if not m: continue return False # check at, ct, mt = os.path.getatime(f), os.path.getctime(f), os.path.getmtime(f) if atimeout is not None and seed - at < atimeout: return False if ctimeout is not None and seed - ct < ctimeout: return False if mtimeout is not None and seed - mt < mtimeout: return False return True # scan all paths include_files = [] for path in paths: for root, dirs, files in os.walk(path): for f in files: file_path = os.path.join(root, f) if not check_include(file_path): continue include_files.append(file_path) if verbose: print(file_path) return include_files def remove_empty_dirs(paths): def _do(path): empty = True for f in os.listdir(path): f = os.path.join(path, f) if os.path.isfile(f): empty = False break if not _do(f): empty = False break return empty for p in paths: _do(p) def clean(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, remove_empty_dir=True, verbose=False): ''' :params: see test method :return: None ''' # find all deleted files files = match(paths, atimeout, ctimeout, mtimeout, seed, patterns, False) # remove files for f in files: try: os.remove(f) except: pass if verbose: print(f) # clear empty directories if remove_empty_dir: remove_empty_dirs(paths) def main(): import argparse class PatternAction(argparse.Action): def __init__(self, *args, **kwargs): super(PatternAction, self).__init__(*args, **kwargs) def __call__(self, parser, namespace, values, option_string=None): if not 'patterns' in namespace: setattr(namespace, 'patterns', []) tag = 'i' if self.dest == 'include' else 'e' namespace.patterns.append((tag, values)) parser = argparse.ArgumentParser(prog='fclean', description="A clean tool for remove timeout files and path") parser.add_argument('-p', '--path', type=str, required=True, action='append', help='Path for clean') parser.add_argument('-t', '--timeout', type=int, help='File will be deleted after timeout') parser.add_argument('-at', '--access-timeout', type=int, help='File will be deleted after last access timeout') parser.add_argument('-ct', '--creation-timeout', type=int, help='File will be deleted after creation timeout') parser.add_argument('-mt', '--modification-timeout', type=int, help='File will be deleted after modification timeout') parser.add_argument('-s', '--seed', type=float, default=None, help='Base line of current time') parser.add_argument('-i', '--include', type=str, action=PatternAction, help='Include files matching PATTERN') parser.add_argument('-e', '--exclude', type=str, action=PatternAction, help='Exclude files matching PATTERN') parser.add_argument('-m', '--match', action='store_true', default=False, help='Only execute match instead of remove files') parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Increase verbosity') parser.add_argument('-k', '--keep', action='store_true', default=False, help='Keep empty directories') args = parser.parse_args() # parse timeout if args.timeout is not None and args.access_timeout is None: args.access_timeout = args.timeout if args.match: match(args.path, args.access_timeout, args.creation_timeout, args.modification_timeout, args.seed, args.patterns, args.verbose) else: clean(args.path, args.access_timeout, args.creation_timeout, args.modification_timeout, args.seed, args.patterns, not args.keep, args.verbose) if __name__ == '__main__': main()
pyplus/tools/file_cleaner.py
import os import time import fnmatch def match(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, verbose=False): ''' :param paths: path for clean :param atimeout: file will be deleted after access timeout :param ctimeout: file will be deleted after creation timeout :param mtimeout: file will be deleted after modification timeout :param seed: base line of current time :param patterns: includes and excludes patterns with format [('i', pattern), ('e', pattern), ...] :return: file list ''' # args check if isinstance(paths, str): paths = [paths] assert isinstance(paths, (tuple, list)) if seed is None: seed = time.time() if patterns is None: patterns = ['i', '*'] # match function def check_include(f): # check patterns for t, p in patterns: m = fnmatch.fnmatch(file_path, p) if t == 'i': if not m: continue break else: if not m: continue return False # check at, ct, mt = os.path.getatime(f), os.path.getctime(f), os.path.getmtime(f) if atimeout is not None and seed - at < atimeout: return False if ctimeout is not None and seed - ct < ctimeout: return False if mtimeout is not None and seed - mt < mtimeout: return False return True # scan all paths include_files = [] for path in paths: for root, dirs, files in os.walk(path): for f in files: file_path = os.path.join(root, f) if not check_include(file_path): continue include_files.append(file_path) if verbose: print(file_path) return include_files def remove_empty_dirs(paths): def _do(path): empty = True for f in os.listdir(path): f = os.path.join(path, f) if os.path.isfile(f): empty = False break if not _do(f): empty = False break return empty for p in paths: _do(p) def clean(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, remove_empty_dir=True, verbose=False): ''' :params: see test method :return: None ''' # find all deleted files files = match(paths, atimeout, ctimeout, mtimeout, seed, patterns, False) # remove files for f in files: try: os.remove(f) except: pass if verbose: print(f) # clear empty directories if remove_empty_dir: remove_empty_dirs(paths) def main(): import argparse class PatternAction(argparse.Action): def __init__(self, *args, **kwargs): super(PatternAction, self).__init__(*args, **kwargs) def __call__(self, parser, namespace, values, option_string=None): if not 'patterns' in namespace: setattr(namespace, 'patterns', []) tag = 'i' if self.dest == 'include' else 'e' namespace.patterns.append((tag, values)) parser = argparse.ArgumentParser(prog='fclean', description="A clean tool for remove timeout files and path") parser.add_argument('-p', '--path', type=str, required=True, action='append', help='Path for clean') parser.add_argument('-t', '--timeout', type=int, help='File will be deleted after timeout') parser.add_argument('-at', '--access-timeout', type=int, help='File will be deleted after last access timeout') parser.add_argument('-ct', '--creation-timeout', type=int, help='File will be deleted after creation timeout') parser.add_argument('-mt', '--modification-timeout', type=int, help='File will be deleted after modification timeout') parser.add_argument('-s', '--seed', type=float, default=None, help='Base line of current time') parser.add_argument('-i', '--include', type=str, action=PatternAction, help='Include files matching PATTERN') parser.add_argument('-e', '--exclude', type=str, action=PatternAction, help='Exclude files matching PATTERN') parser.add_argument('-m', '--match', action='store_true', default=False, help='Only execute match instead of remove files') parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Increase verbosity') parser.add_argument('-k', '--keep', action='store_true', default=False, help='Keep empty directories') args = parser.parse_args() # parse timeout if args.timeout is not None and args.access_timeout is None: args.access_timeout = args.timeout if args.match: match(args.path, args.access_timeout, args.creation_timeout, args.modification_timeout, args.seed, args.patterns, args.verbose) else: clean(args.path, args.access_timeout, args.creation_timeout, args.modification_timeout, args.seed, args.patterns, not args.keep, args.verbose) if __name__ == '__main__': main()
0.205894
0.160496
from assets.variables import * import assets.tools as tools from scenes import editor, helper, options class MainMenu(tools.SceneBase): """Class that creates the main menu screen Attributes ---------- counter: int keeps track of the user's selection selection: dict uses the counter to get the object of the user's current selection Methods ---------- process_input(events, pressed_keys): Handles input update(): Updates scene render(screen): Renders the helper's UI """ def __init__(self) -> None: """Initialize class attributes Returns ---------- None """ tools.SceneBase.__init__(self) # Sets the counter self.counter = 0 self.selection = {0: "start", 1: "help", 2: "options", 3: "quit"} def process_input(self, events, pressed_keys) -> None: """Handles input Parameters ---------- events: int the different game events pressed_keys: str the keys pressed by the user Returns ---------- None """ for event in events: if event.type == pg.KEYDOWN: # Checks if down arrow is pressed if event.key == pg.K_DOWN: if self.counter < 3: self.counter += 1 # Checks if up arrow is pressed elif event.key == pg.K_UP: if self.counter > 0: self.counter -= 1 # Checks if enter is pressed if event.key == pg.K_RETURN: if self.selection[self.counter] == "start": self.switch_to_scene(editor.Editor()) elif self.selection[self.counter] == "help": self.switch_to_scene(helper.Help()) elif self.selection[self.counter] == "options": self.switch_to_scene(options.Options()) elif self.selection[self.counter] == "quit": self.terminate() def update(self) -> None: """Updates scene Returns ---------- None """ pass def render(self, screen) -> None: """Renders the menu's UI Parameters ---------- screen the screen pygame displays on Returns ---------- None """ # Fills screen screen.fill(BLACK) # Sets titles and main menu options title = tools.text_format("Universum - Sim", 90, RED) if self.selection[self.counter] == "start": text_start = tools.text_format("START", 75, GREEN) else: text_start = tools.text_format("START", 75, WHITE) if self.selection[self.counter] == "help": text_help = tools.text_format("HELP", 75, GREEN) else: text_help = tools.text_format("HELP", 75, WHITE) if self.selection[self.counter] == "options": text_options = tools.text_format("OPTIONS", 75, GREEN) else: text_options = tools.text_format("OPTIONS", 75, WHITE) if self.selection[self.counter] == "quit": text_quit = tools.text_format("QUIT", 75, GREEN) else: text_quit = tools.text_format("QUIT", 75, WHITE) title_rect = title.get_rect() start_rect = text_start.get_rect() help_rect = text_help.get_rect() options_rect = text_options.get_rect() quit_rect = text_quit.get_rect() # Main Menu Text screen.blit(title, (SCREEN_WIDTH / 2 - (title_rect[2] / 2), 80)) screen.blit(text_start, (SCREEN_WIDTH / 2 - (start_rect[2] / 2), 300)) screen.blit(text_help, (SCREEN_WIDTH / 2 - (help_rect[2] / 2), 380)) screen.blit(text_options, (SCREEN_WIDTH / 2 - (options_rect[2] / 2), 460)) screen.blit(text_quit, (SCREEN_WIDTH / 2 - (quit_rect[2] / 2), 540))
scripts/scenes/menu.py
from assets.variables import * import assets.tools as tools from scenes import editor, helper, options class MainMenu(tools.SceneBase): """Class that creates the main menu screen Attributes ---------- counter: int keeps track of the user's selection selection: dict uses the counter to get the object of the user's current selection Methods ---------- process_input(events, pressed_keys): Handles input update(): Updates scene render(screen): Renders the helper's UI """ def __init__(self) -> None: """Initialize class attributes Returns ---------- None """ tools.SceneBase.__init__(self) # Sets the counter self.counter = 0 self.selection = {0: "start", 1: "help", 2: "options", 3: "quit"} def process_input(self, events, pressed_keys) -> None: """Handles input Parameters ---------- events: int the different game events pressed_keys: str the keys pressed by the user Returns ---------- None """ for event in events: if event.type == pg.KEYDOWN: # Checks if down arrow is pressed if event.key == pg.K_DOWN: if self.counter < 3: self.counter += 1 # Checks if up arrow is pressed elif event.key == pg.K_UP: if self.counter > 0: self.counter -= 1 # Checks if enter is pressed if event.key == pg.K_RETURN: if self.selection[self.counter] == "start": self.switch_to_scene(editor.Editor()) elif self.selection[self.counter] == "help": self.switch_to_scene(helper.Help()) elif self.selection[self.counter] == "options": self.switch_to_scene(options.Options()) elif self.selection[self.counter] == "quit": self.terminate() def update(self) -> None: """Updates scene Returns ---------- None """ pass def render(self, screen) -> None: """Renders the menu's UI Parameters ---------- screen the screen pygame displays on Returns ---------- None """ # Fills screen screen.fill(BLACK) # Sets titles and main menu options title = tools.text_format("Universum - Sim", 90, RED) if self.selection[self.counter] == "start": text_start = tools.text_format("START", 75, GREEN) else: text_start = tools.text_format("START", 75, WHITE) if self.selection[self.counter] == "help": text_help = tools.text_format("HELP", 75, GREEN) else: text_help = tools.text_format("HELP", 75, WHITE) if self.selection[self.counter] == "options": text_options = tools.text_format("OPTIONS", 75, GREEN) else: text_options = tools.text_format("OPTIONS", 75, WHITE) if self.selection[self.counter] == "quit": text_quit = tools.text_format("QUIT", 75, GREEN) else: text_quit = tools.text_format("QUIT", 75, WHITE) title_rect = title.get_rect() start_rect = text_start.get_rect() help_rect = text_help.get_rect() options_rect = text_options.get_rect() quit_rect = text_quit.get_rect() # Main Menu Text screen.blit(title, (SCREEN_WIDTH / 2 - (title_rect[2] / 2), 80)) screen.blit(text_start, (SCREEN_WIDTH / 2 - (start_rect[2] / 2), 300)) screen.blit(text_help, (SCREEN_WIDTH / 2 - (help_rect[2] / 2), 380)) screen.blit(text_options, (SCREEN_WIDTH / 2 - (options_rect[2] / 2), 460)) screen.blit(text_quit, (SCREEN_WIDTH / 2 - (quit_rect[2] / 2), 540))
0.758779
0.348146
r""" Copyright (c) 2015 <NAME> This software is released under the MIT License. http://opensource.org/licenses/mit-license.php """ __author__ = 'mori.yuichiro' import time import pprint import logging import json import argparse import tempfile import boto from boto.s3.key import Key from crypt import Encryptor from filelister import FileLister from flock import SimpleFileLock from util import * CONFIG_DIR = '.s4backup' CONFIG_FILE_NAME = 'config.json' IGNORE_FILE_NAME = 'file_ignore' IGNORE_DIR_NAME = 'dir_ignore' LOCK_FILE_NAME = 'lock' IGNORE_FILE_RULES = [ '.DS_Store', '*~', ] IGNORE_DIRS = [ '.git', '.idea', CONFIG_DIR ] class S4Backupper(): def __init__(self, target_path, aws_access_key_id, aws_secret_access_key, s3bucket_name, s3prefix, use_hash_filename=False, use_encryption=False, key_str=None, iv_str=None, aws_region=None, dry_run_flg=False): abs_path = os.path.abspath(target_path) if not os.path.isdir(abs_path): raise Exception('Invalid target path!') self.target_path = abs_path self.snapshot_version = time.strftime('%Y-%m-%d_%H-%M-%S', time.gmtime(time.time())) # *** directoy initialization *** log_base_path = os.path.join(abs_path, CONFIG_DIR, 'logs') mkdir_p(log_base_path) log_path = os.path.join(log_base_path, self.snapshot_version) mkdir_p(log_path) self.log_path = log_path self.stats = { 'bytes_uploaded': 0, 'bytes_scanned': 0, 'files_uploaded': 0, 'files_scanned': 0, 'bytes_total': 0, 'files_total': 0, } self.s3keys = {} # *** AWS S3 Connection *** self.s3conn = boto.s3.connect_to_region( aws_region or 'us-east-1', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) self.s3bucket = self.s3conn.get_bucket(s3bucket_name) self.s3prefix = str(s3prefix) # get lid of unicode self.dry_run_flg = dry_run_flg # *** Logger *** # Logger to show progress logger = logging.getLogger('S3ArchiverStdout') logger.setLevel(logging.DEBUG) h = logging.StreamHandler() h.setLevel(logging.INFO) h.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s")) logger.addHandler(h) h2 = logging.FileHandler(os.path.join(self.log_path, 'detail.log')) h2.setLevel(logging.DEBUG) h2.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s")) logger.addHandler(h2) self.logger = logger self.file_lister = FileLister( self.target_path, ignore_dirs=IGNORE_DIRS, ignore_file_patterns=IGNORE_FILE_RULES, ) self.update_count = 0 self.hash_filename_flg = use_hash_filename self.encryption_flg = use_encryption if self.encryption_flg: self.encryptor = Encryptor.initialize_by_hex(key_str, iv_str) else: self.encryptor = None def _backup_file(self, file_path, upload_path): with tempfile.TemporaryFile() as out_file_p: with open(file_path, 'rb') as in_file_p: file_backp_start_time = time.time() (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file_path) encryption_seconds = 0 encrypted_size = 0 if self.encryption_flg: encryption_start_time = time.time() self.encryptor.encrypt_file(in_file_p, out_file_p) encryption_seconds = time.time() - encryption_start_time encrypted_size = out_file_p.tell() in_file_p.seek(0, os.SEEK_SET) out_file_p.seek(0, os.SEEK_SET) md5_start_time = time.time() md5sum = calc_md5_from_file(out_file_p) md5_seconds = time.time() - md5_start_time out_file_p.seek(0, os.SEEK_SET) log_parts = [ 'file=%s' % file_path, 'path=%s' % upload_path, 'md5=%s' % md5sum, 'size=%s' % size, 'enc_size=%s' % encrypted_size, 'enc_sec={:.3f}'.format(encryption_seconds), 'md5_sec={:.3f}'.format(md5_seconds), ] self.logger.debug(' '.join(log_parts)) self.stats['files_scanned'] += 1 self.stats['bytes_scanned'] += size s3path = '/'.join([self.s3prefix, upload_path]) if s3path in self.s3keys: cached_key = self.s3keys[s3path] if cached_key.etag == '"%s"' % md5sum: self.logger.debug('%s/%s skipped file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) return fkey = self.s3bucket.get_key(s3path) if fkey and fkey.etag == '"%s"' % md5sum: self.logger.debug('%s/%s checked and skipped file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) return # file does not exist or modified if self.dry_run_flg: self.logger.warn('Upload skipped due to dry run flg file:%s' % upload_path) return obj_key = Key(self.s3bucket) obj_key.key = s3path obj_key.set_metadata('original_size', str(size)) obj_key.set_contents_from_file(out_file_p, encrypt_key=True) self.stats['files_uploaded'] += 1 self.stats['bytes_uploaded'] += size self.logger.debug('%s/%s uploaded file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) def _auto_log_update(self): self.update_count += 1 if self.update_count % 20 != 0: return bytes_total = self.stats['bytes_total'] bytes_uploaded = self.stats['bytes_uploaded'] bytes_scanned = self.stats['bytes_scanned'] self.logger.info( 'Bytes uploaded:{}({:.2f}%) '.format(humanize_bytes(bytes_uploaded), percentize(bytes_uploaded, bytes_total)) + 'scanned:{}({:.2f}%) '.format(humanize_bytes(bytes_scanned), percentize(bytes_scanned, bytes_total)) + 'total:{} '.format(humanize_bytes(self.stats['bytes_total'])) + '' ) files_total = self.stats['files_total'] if files_total == 0: files_total = 1 files_uploaded = self.stats['files_uploaded'] files_scanned = self.stats['files_scanned'] self.logger.info( 'Files uploaded:{}({:.2f}%) '.format(files_uploaded, percentize(files_uploaded, files_total)) + 'scanned:{}({:.2f}%) '.format(files_scanned, percentize(files_scanned, files_total)) + 'total:{} '.format(files_total) + '' ) def _save_directory_state(self, files): state_file_path = os.path.join(self.log_path, 'state.txt') with open(state_file_path, 'wt') as f: bytes_total = 0 files_total = 0 for found_file in files: relative_path = found_file.replace(self.target_path + '/', "", 1) (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(found_file) parts = [ 'path=%s' % relative_path, 'size=%s' % size, 'ctime=%s' % ctime, 'mtime=%s' % mtime, ] line = '\t'.join(parts) + '\n' f.write(line) bytes_total += size files_total += 1 self.stats['bytes_total'] = bytes_total self.stats['files_total'] = files_total upload_path = '/'.join(['logs', self.snapshot_version, 'state.txt']) self._backup_file(state_file_path, upload_path) def _execute_backup(self): self.logger.info('Snapshot version:%s' % self.snapshot_version) time_start = time.time() s3path = '/'.join([self.s3prefix, 'data']) key_num = 0 for fkey in self.s3bucket.list(s3path): self.s3keys[fkey.key.encode('utf-8')] = fkey key_num += 1 self.logger.info('Cached keys:%s' % key_num) files = self.file_lister.get_file_list() self._save_directory_state(files) for found_file in files: relative_path = found_file.replace(self.target_path + '/', "", 1) if self.hash_filename_flg: relative_path = calc_sha1_from_str(relative_path) self._backup_file(found_file, '/'.join(['data', relative_path])) self._auto_log_update() self.logger.info('Bytes uploaded:%s scanned:%s total:%s' % (self.stats['bytes_uploaded'], self.stats['bytes_scanned'], self.stats['bytes_total'])) self.logger.info('Files uploaded:%s scanned:%s total:%s' % (self.stats['files_uploaded'], self.stats['files_scanned'], self.stats['files_total'])) time_end = time.time() summary_file_path = os.path.join(self.log_path, 'summary.txt') with open(summary_file_path, 'wt') as f: f.write('time_start :%s (%s)\n' % (time.strftime('%Y-%m-%d %H-%M-%S', time.gmtime(time_start)), time_start)) f.write('time_end :%s (%s)\n' % (time.strftime('%Y-%m-%d %H-%M-%S', time.gmtime(time_end)), time_end)) seconds_spent = time_end - time_start f.write('seconds_spent:%s\n' % (seconds_spent)) f.write('\n') f.write('Bytes uploaded:%s scanned:%s total:%s\n' % (self.stats['bytes_uploaded'], self.stats['bytes_scanned'], self.stats['bytes_total'])) f.write('Files uploaded:%s scanned:%s total:%s\n' % (self.stats['files_uploaded'], self.stats['files_scanned'], self.stats['files_total'])) upload_path = '/'.join(['logs', self.snapshot_version, 'summary.txt']) self._backup_file(summary_file_path, upload_path) def execute_backup(self): locker = SimpleFileLock(os.path.join(self.target_path, CONFIG_DIR, LOCK_FILE_NAME)) if not locker.aquire_lock(): self.logger.error('Cannot get lock!') return try: self._execute_backup() except Exception as e: self.logger.exception(e) raise e finally: locker.release() def init(): config_path = os.path.join(os.getcwd(), CONFIG_DIR) config_json_path = os.path.join(config_path, CONFIG_FILE_NAME) file_ignore_path = os.path.join(config_path, IGNORE_FILE_NAME) dir_ignore_path = os.path.join(config_path, IGNORE_DIR_NAME) if not os.path.isdir(config_path): os.mkdir(config_path) if not os.path.isfile(config_json_path): with open(config_json_path, 'wt') as f: json.dump({}, f) if not os.path.isfile(file_ignore_path): with open(file_ignore_path, 'wt') as f: f.write('') if not os.path.isfile(dir_ignore_path): with open(dir_ignore_path, 'wt') as f: f.write('') print('Initialization finished!') def _assure_initialized(): config_path = os.path.join(os.getcwd(), CONFIG_DIR) config_json_path = os.path.join(config_path, CONFIG_FILE_NAME) if not os.path.isdir(config_path) or not os.path.isfile(config_json_path): raise Exception('Current working directory is not initialized!') def config(args_obj): _assure_initialized() config_json_path = os.path.join(os.getcwd(), CONFIG_DIR, CONFIG_FILE_NAME) with open(config_json_path) as f: config_dict = json.load(f) if not args_obj.list and 'set' in args_obj and args_obj.set is not None: set_values = args_obj.set key = set_values[0] value = set_values[1] if value == '': config_dict.pop(key, None) else: config_dict[key] = value with open(config_json_path, 'wt') as f: json.dump(config_dict, f) print('%s is set to %s' % (key, value)) return if not args_obj.list and args_obj.keyg: if config_dict.get('encryption', False): raise Exception('Encryption is already turned on!') iv_str, key_str = Encryptor.generate_str_keyset(1) config_dict['encryption'] = 'true' config_dict['iv'] = iv_str config_dict['key'] = key_str with open(config_json_path, 'wt') as f: json.dump(config_dict, f) print('encryption is turned on') print('key %s' % key_str) print('iv %s' % iv_str) return for key in sorted(config_dict.keys()): print('%s=%s' % (key, config_dict[key])) def execute_backup(dry_run_flg): _assure_initialized() config_json_path = os.path.join(os.getcwd(), CONFIG_DIR, CONFIG_FILE_NAME) with open(config_json_path) as f: config_dict = json.load(f) if 'aws_access_key_id' in config_dict: aws_access_key_id = config_dict['aws_access_key_id'] else: aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID') if 'aws_secret_access_key' in config_dict: aws_secret_access_key = config_dict['aws_secret_access_key'] else: aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY') encryption_value = config_dict.get('encryption', None) if encryption_value and encryption_value.lower() == 'true': encryption_flg = True else: encryption_flg = False hash_filename = config_dict.get('hash_filename', None) if hash_filename and hash_filename.lower() == 'true': hash_filename_flg = True else: hash_filename_flg = False backupper = S4Backupper( target_path=os.getcwd(), aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_region=config_dict.get('aws_region', None), s3bucket_name=config_dict['s3bucket'], s3prefix=config_dict['s3prefix'], use_hash_filename=hash_filename_flg, use_encryption=encryption_flg, key_str=config_dict.get('key', ''), iv_str=config_dict.get('iv', ''), dry_run_flg=dry_run_flg, ) backupper.execute_backup() if __name__ == '__main__': parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="subparser", help='sub-command help') parser_init = subparsers.add_parser('init', help='initialize current working directory as backup target') parser_config = subparsers.add_parser('config', help='list / set current working directory config') parser_config.add_argument('-l', '--list', dest='list', action='store_true', help='List') parser_config.add_argument('-s', '--set', nargs=2, dest='set', help='Set') parser_config.add_argument('-k', '--key', dest='keyg', action='store_true', help='Generate encryption key') parser_push = subparsers.add_parser('push', help='execute backup against current working directory') parser_push.add_argument('-d', '--dry', dest='dry_run', action='store_true', help='Dry run') parsed_args = parser.parse_args() if parsed_args.subparser == 'init': init() elif parsed_args.subparser == 'config': config(parsed_args) else: execute_backup(parsed_args.dry_run)
s4backup.py
r""" Copyright (c) 2015 <NAME> This software is released under the MIT License. http://opensource.org/licenses/mit-license.php """ __author__ = 'mori.yuichiro' import time import pprint import logging import json import argparse import tempfile import boto from boto.s3.key import Key from crypt import Encryptor from filelister import FileLister from flock import SimpleFileLock from util import * CONFIG_DIR = '.s4backup' CONFIG_FILE_NAME = 'config.json' IGNORE_FILE_NAME = 'file_ignore' IGNORE_DIR_NAME = 'dir_ignore' LOCK_FILE_NAME = 'lock' IGNORE_FILE_RULES = [ '.DS_Store', '*~', ] IGNORE_DIRS = [ '.git', '.idea', CONFIG_DIR ] class S4Backupper(): def __init__(self, target_path, aws_access_key_id, aws_secret_access_key, s3bucket_name, s3prefix, use_hash_filename=False, use_encryption=False, key_str=None, iv_str=None, aws_region=None, dry_run_flg=False): abs_path = os.path.abspath(target_path) if not os.path.isdir(abs_path): raise Exception('Invalid target path!') self.target_path = abs_path self.snapshot_version = time.strftime('%Y-%m-%d_%H-%M-%S', time.gmtime(time.time())) # *** directoy initialization *** log_base_path = os.path.join(abs_path, CONFIG_DIR, 'logs') mkdir_p(log_base_path) log_path = os.path.join(log_base_path, self.snapshot_version) mkdir_p(log_path) self.log_path = log_path self.stats = { 'bytes_uploaded': 0, 'bytes_scanned': 0, 'files_uploaded': 0, 'files_scanned': 0, 'bytes_total': 0, 'files_total': 0, } self.s3keys = {} # *** AWS S3 Connection *** self.s3conn = boto.s3.connect_to_region( aws_region or 'us-east-1', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) self.s3bucket = self.s3conn.get_bucket(s3bucket_name) self.s3prefix = str(s3prefix) # get lid of unicode self.dry_run_flg = dry_run_flg # *** Logger *** # Logger to show progress logger = logging.getLogger('S3ArchiverStdout') logger.setLevel(logging.DEBUG) h = logging.StreamHandler() h.setLevel(logging.INFO) h.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s")) logger.addHandler(h) h2 = logging.FileHandler(os.path.join(self.log_path, 'detail.log')) h2.setLevel(logging.DEBUG) h2.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s")) logger.addHandler(h2) self.logger = logger self.file_lister = FileLister( self.target_path, ignore_dirs=IGNORE_DIRS, ignore_file_patterns=IGNORE_FILE_RULES, ) self.update_count = 0 self.hash_filename_flg = use_hash_filename self.encryption_flg = use_encryption if self.encryption_flg: self.encryptor = Encryptor.initialize_by_hex(key_str, iv_str) else: self.encryptor = None def _backup_file(self, file_path, upload_path): with tempfile.TemporaryFile() as out_file_p: with open(file_path, 'rb') as in_file_p: file_backp_start_time = time.time() (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file_path) encryption_seconds = 0 encrypted_size = 0 if self.encryption_flg: encryption_start_time = time.time() self.encryptor.encrypt_file(in_file_p, out_file_p) encryption_seconds = time.time() - encryption_start_time encrypted_size = out_file_p.tell() in_file_p.seek(0, os.SEEK_SET) out_file_p.seek(0, os.SEEK_SET) md5_start_time = time.time() md5sum = calc_md5_from_file(out_file_p) md5_seconds = time.time() - md5_start_time out_file_p.seek(0, os.SEEK_SET) log_parts = [ 'file=%s' % file_path, 'path=%s' % upload_path, 'md5=%s' % md5sum, 'size=%s' % size, 'enc_size=%s' % encrypted_size, 'enc_sec={:.3f}'.format(encryption_seconds), 'md5_sec={:.3f}'.format(md5_seconds), ] self.logger.debug(' '.join(log_parts)) self.stats['files_scanned'] += 1 self.stats['bytes_scanned'] += size s3path = '/'.join([self.s3prefix, upload_path]) if s3path in self.s3keys: cached_key = self.s3keys[s3path] if cached_key.etag == '"%s"' % md5sum: self.logger.debug('%s/%s skipped file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) return fkey = self.s3bucket.get_key(s3path) if fkey and fkey.etag == '"%s"' % md5sum: self.logger.debug('%s/%s checked and skipped file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) return # file does not exist or modified if self.dry_run_flg: self.logger.warn('Upload skipped due to dry run flg file:%s' % upload_path) return obj_key = Key(self.s3bucket) obj_key.key = s3path obj_key.set_metadata('original_size', str(size)) obj_key.set_contents_from_file(out_file_p, encrypt_key=True) self.stats['files_uploaded'] += 1 self.stats['bytes_uploaded'] += size self.logger.debug('%s/%s uploaded file=%s' % (self.stats['files_scanned'], self.stats['files_total'], upload_path)) def _auto_log_update(self): self.update_count += 1 if self.update_count % 20 != 0: return bytes_total = self.stats['bytes_total'] bytes_uploaded = self.stats['bytes_uploaded'] bytes_scanned = self.stats['bytes_scanned'] self.logger.info( 'Bytes uploaded:{}({:.2f}%) '.format(humanize_bytes(bytes_uploaded), percentize(bytes_uploaded, bytes_total)) + 'scanned:{}({:.2f}%) '.format(humanize_bytes(bytes_scanned), percentize(bytes_scanned, bytes_total)) + 'total:{} '.format(humanize_bytes(self.stats['bytes_total'])) + '' ) files_total = self.stats['files_total'] if files_total == 0: files_total = 1 files_uploaded = self.stats['files_uploaded'] files_scanned = self.stats['files_scanned'] self.logger.info( 'Files uploaded:{}({:.2f}%) '.format(files_uploaded, percentize(files_uploaded, files_total)) + 'scanned:{}({:.2f}%) '.format(files_scanned, percentize(files_scanned, files_total)) + 'total:{} '.format(files_total) + '' ) def _save_directory_state(self, files): state_file_path = os.path.join(self.log_path, 'state.txt') with open(state_file_path, 'wt') as f: bytes_total = 0 files_total = 0 for found_file in files: relative_path = found_file.replace(self.target_path + '/', "", 1) (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(found_file) parts = [ 'path=%s' % relative_path, 'size=%s' % size, 'ctime=%s' % ctime, 'mtime=%s' % mtime, ] line = '\t'.join(parts) + '\n' f.write(line) bytes_total += size files_total += 1 self.stats['bytes_total'] = bytes_total self.stats['files_total'] = files_total upload_path = '/'.join(['logs', self.snapshot_version, 'state.txt']) self._backup_file(state_file_path, upload_path) def _execute_backup(self): self.logger.info('Snapshot version:%s' % self.snapshot_version) time_start = time.time() s3path = '/'.join([self.s3prefix, 'data']) key_num = 0 for fkey in self.s3bucket.list(s3path): self.s3keys[fkey.key.encode('utf-8')] = fkey key_num += 1 self.logger.info('Cached keys:%s' % key_num) files = self.file_lister.get_file_list() self._save_directory_state(files) for found_file in files: relative_path = found_file.replace(self.target_path + '/', "", 1) if self.hash_filename_flg: relative_path = calc_sha1_from_str(relative_path) self._backup_file(found_file, '/'.join(['data', relative_path])) self._auto_log_update() self.logger.info('Bytes uploaded:%s scanned:%s total:%s' % (self.stats['bytes_uploaded'], self.stats['bytes_scanned'], self.stats['bytes_total'])) self.logger.info('Files uploaded:%s scanned:%s total:%s' % (self.stats['files_uploaded'], self.stats['files_scanned'], self.stats['files_total'])) time_end = time.time() summary_file_path = os.path.join(self.log_path, 'summary.txt') with open(summary_file_path, 'wt') as f: f.write('time_start :%s (%s)\n' % (time.strftime('%Y-%m-%d %H-%M-%S', time.gmtime(time_start)), time_start)) f.write('time_end :%s (%s)\n' % (time.strftime('%Y-%m-%d %H-%M-%S', time.gmtime(time_end)), time_end)) seconds_spent = time_end - time_start f.write('seconds_spent:%s\n' % (seconds_spent)) f.write('\n') f.write('Bytes uploaded:%s scanned:%s total:%s\n' % (self.stats['bytes_uploaded'], self.stats['bytes_scanned'], self.stats['bytes_total'])) f.write('Files uploaded:%s scanned:%s total:%s\n' % (self.stats['files_uploaded'], self.stats['files_scanned'], self.stats['files_total'])) upload_path = '/'.join(['logs', self.snapshot_version, 'summary.txt']) self._backup_file(summary_file_path, upload_path) def execute_backup(self): locker = SimpleFileLock(os.path.join(self.target_path, CONFIG_DIR, LOCK_FILE_NAME)) if not locker.aquire_lock(): self.logger.error('Cannot get lock!') return try: self._execute_backup() except Exception as e: self.logger.exception(e) raise e finally: locker.release() def init(): config_path = os.path.join(os.getcwd(), CONFIG_DIR) config_json_path = os.path.join(config_path, CONFIG_FILE_NAME) file_ignore_path = os.path.join(config_path, IGNORE_FILE_NAME) dir_ignore_path = os.path.join(config_path, IGNORE_DIR_NAME) if not os.path.isdir(config_path): os.mkdir(config_path) if not os.path.isfile(config_json_path): with open(config_json_path, 'wt') as f: json.dump({}, f) if not os.path.isfile(file_ignore_path): with open(file_ignore_path, 'wt') as f: f.write('') if not os.path.isfile(dir_ignore_path): with open(dir_ignore_path, 'wt') as f: f.write('') print('Initialization finished!') def _assure_initialized(): config_path = os.path.join(os.getcwd(), CONFIG_DIR) config_json_path = os.path.join(config_path, CONFIG_FILE_NAME) if not os.path.isdir(config_path) or not os.path.isfile(config_json_path): raise Exception('Current working directory is not initialized!') def config(args_obj): _assure_initialized() config_json_path = os.path.join(os.getcwd(), CONFIG_DIR, CONFIG_FILE_NAME) with open(config_json_path) as f: config_dict = json.load(f) if not args_obj.list and 'set' in args_obj and args_obj.set is not None: set_values = args_obj.set key = set_values[0] value = set_values[1] if value == '': config_dict.pop(key, None) else: config_dict[key] = value with open(config_json_path, 'wt') as f: json.dump(config_dict, f) print('%s is set to %s' % (key, value)) return if not args_obj.list and args_obj.keyg: if config_dict.get('encryption', False): raise Exception('Encryption is already turned on!') iv_str, key_str = Encryptor.generate_str_keyset(1) config_dict['encryption'] = 'true' config_dict['iv'] = iv_str config_dict['key'] = key_str with open(config_json_path, 'wt') as f: json.dump(config_dict, f) print('encryption is turned on') print('key %s' % key_str) print('iv %s' % iv_str) return for key in sorted(config_dict.keys()): print('%s=%s' % (key, config_dict[key])) def execute_backup(dry_run_flg): _assure_initialized() config_json_path = os.path.join(os.getcwd(), CONFIG_DIR, CONFIG_FILE_NAME) with open(config_json_path) as f: config_dict = json.load(f) if 'aws_access_key_id' in config_dict: aws_access_key_id = config_dict['aws_access_key_id'] else: aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID') if 'aws_secret_access_key' in config_dict: aws_secret_access_key = config_dict['aws_secret_access_key'] else: aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY') encryption_value = config_dict.get('encryption', None) if encryption_value and encryption_value.lower() == 'true': encryption_flg = True else: encryption_flg = False hash_filename = config_dict.get('hash_filename', None) if hash_filename and hash_filename.lower() == 'true': hash_filename_flg = True else: hash_filename_flg = False backupper = S4Backupper( target_path=os.getcwd(), aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_region=config_dict.get('aws_region', None), s3bucket_name=config_dict['s3bucket'], s3prefix=config_dict['s3prefix'], use_hash_filename=hash_filename_flg, use_encryption=encryption_flg, key_str=config_dict.get('key', ''), iv_str=config_dict.get('iv', ''), dry_run_flg=dry_run_flg, ) backupper.execute_backup() if __name__ == '__main__': parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="subparser", help='sub-command help') parser_init = subparsers.add_parser('init', help='initialize current working directory as backup target') parser_config = subparsers.add_parser('config', help='list / set current working directory config') parser_config.add_argument('-l', '--list', dest='list', action='store_true', help='List') parser_config.add_argument('-s', '--set', nargs=2, dest='set', help='Set') parser_config.add_argument('-k', '--key', dest='keyg', action='store_true', help='Generate encryption key') parser_push = subparsers.add_parser('push', help='execute backup against current working directory') parser_push.add_argument('-d', '--dry', dest='dry_run', action='store_true', help='Dry run') parsed_args = parser.parse_args() if parsed_args.subparser == 'init': init() elif parsed_args.subparser == 'config': config(parsed_args) else: execute_backup(parsed_args.dry_run)
0.414306
0.070848
import geopandas as gpd import scipy.optimize import scipy.sparse def match_footprints(grnd_df, prop_df, threshold=0.25, base_reward=100.): """ Optimal matching of ground truth footprints with proposal footprints (for a single timestep). Input dataframes should have "id" & "geometry" columns. """ # Supplement IDs with indices (which run from zero # to one less than the number of unique IDs) grnd_id_set = set(grnd_df['id']) prop_id_set = set(prop_df['id']) grnd_id_to_index = {id: index for index, id in enumerate(sorted(list(grnd_id_set)))} prop_id_to_index = {id: index for index, id in enumerate(sorted(list(prop_id_set)))} grnd_index_to_id = {index: id for id, index in grnd_id_to_index.items()} prop_index_to_id = {index: id for id, index in prop_id_to_index.items()} grnd_df['index'] = grnd_df.id.apply(lambda id: grnd_id_to_index[id]) prop_df['index'] = prop_df.id.apply(lambda id: prop_id_to_index[id]) # Calculate IOU for all intersections, and the corresponding reward grnd_df['grnd_area'] = grnd_df.area prop_df['prop_area'] = prop_df.area if not (grnd_df.empty or prop_df.empty): intersect = gpd.overlay(grnd_df, prop_df) else: intersect = None if intersect is None or len(intersect) == 0: return [], [], len(grnd_df), len(prop_df), 0, len(prop_df), len(grnd_df), 0., grnd_id_set, prop_id_set intersect['inter_area'] = intersect.area intersect['iou'] = intersect['inter_area'] / (intersect['grnd_area'] + intersect['prop_area'] - intersect['inter_area']) intersect['reward'] = intersect.apply(lambda row: (row.iou > threshold) * (base_reward + row.iou), axis=1) # Convert IOUs and rewards to 2D arrays (by way of sparse matrices) iou_matrix = scipy.sparse.coo_matrix((intersect.iou, (intersect.index_1, intersect.index_2)), shape=(len(grnd_df), len(prop_df))) iou_arr = iou_matrix.toarray() reward_matrix = scipy.sparse.coo_matrix((intersect.reward, (intersect.index_1, intersect.index_2)), shape=(len(grnd_df), len(prop_df))) reward_arr = reward_matrix.toarray() # Solve unbalanced linear assignment problem grnd_match, prop_match = scipy.optimize.linear_sum_assignment(reward_arr, maximize=True) iou_match = iou_arr[grnd_match, prop_match] # Remove matches that don't actually contribute to the total score grnd_match_pruned = grnd_match[iou_match>threshold] prop_match_pruned = prop_match[iou_match>threshold] iou_match_pruned = iou_match[iou_match>threshold] # Look up IDs for each match, and calculate descriptive statistics grnd_match_ids = [grnd_index_to_id[index] for index in grnd_match_pruned] prop_match_ids = [prop_index_to_id[index] for index in prop_match_pruned] num_grnd = len(grnd_df) num_prop = len(prop_df) tp = len(iou_match_pruned) fp = num_prop - tp fn = num_grnd - tp if 2*tp + fp + fn > 0: f1 = (2*tp) / (2*tp + fp + fn) else: f1 = 0 return grnd_match_ids, prop_match_ids, num_grnd, num_prop, tp, fp, fn, f1, grnd_id_set, prop_id_set def scot_one_aoi(grnd_df, prop_df, threshold=0.25, base_reward=100., beta=2., stats=False, verbose=False): """ SpaceNet Change and Object Tracking (SCOT) metric, for one AOI. Input dataframes should have "timestep", "id", & "geometry" columns. """ # Get list of timesteps from ground truth and proposal dataframes grnd_timestep_set = set(grnd_df.timestep.drop_duplicates()) prop_timestep_set = set(grnd_df.timestep.drop_duplicates()) timesteps = sorted(list(grnd_timestep_set.union(prop_timestep_set))) # Loop through timesteps if verbose: print('Matching footprints') tp_net = 0 fp_net = 0 fn_net = 0 num_grnd_net = 0 num_prop_net = 0 all_grnd_ids = [] all_prop_ids = [] change_tp_net = 0 change_fp_net = 0 change_fn_net = 0 change_grnd_ids = set() change_prop_ids = set() for i, timestep in enumerate(timesteps): # Get just the data for this timestep grnd_df_one_timestep = grnd_df.loc[grnd_df.timestep == timestep].copy() prop_df_one_timestep = prop_df.loc[prop_df.timestep == timestep].copy() # Find footprint matches for this timestep grnd_ids, prop_ids, num_grnd, num_prop, tp, fp, fn, f1, grnd_id_set, prop_id_set = match_footprints( grnd_df_one_timestep, prop_df_one_timestep, threshold=threshold, base_reward=base_reward) # Collect aggregate statistics for tracking, and retain all match IDs tp_net += tp fp_net += fp fn_net += fn num_grnd_net += num_grnd num_prop_net += num_prop all_grnd_ids = grnd_ids + all_grnd_ids # newest first all_prop_ids = prop_ids + all_prop_ids # newest first if verbose: print(' %2i: F1 = %.4f' % (i + 1, f1)) # Collect aggregate statistics for change detection if i > 0: # Find change detection TPs, FPs, and FNs among matched footprints new_grnd = [grnd_id not in change_grnd_ids for grnd_id in grnd_ids] new_prop = [prop_id not in change_prop_ids for prop_id in prop_ids] change_tp_list = [g and p for g, p in zip(new_grnd, new_prop)] change_fp_list = [p and not g for g, p in zip(new_grnd, new_prop)] change_fn_list = [g and not p for g, p in zip(new_grnd, new_prop)] change_tp_net += sum(change_tp_list) change_fp_net += sum(change_fp_list) change_fn_net += sum(change_fn_list) # Find change detection FPs and FNs among unmatched footprints unmatched_fp = prop_id_set.difference(prop_ids).difference(change_prop_ids) unmatched_fn = grnd_id_set.difference(grnd_ids).difference(change_grnd_ids) change_fp_net += len(unmatched_fp) change_fn_net += len(unmatched_fn) change_grnd_ids = change_grnd_ids.union(grnd_id_set) change_prop_ids = change_prop_ids.union(prop_id_set) # Identify which matches are mismatches # (i.e., inconsistent with previous timesteps) if verbose: print('Identifying mismatches') mm_net = 0 for i in range(len(all_grnd_ids)): grnd_id = all_grnd_ids[i] prop_id = all_prop_ids[i] previous_grnd_ids = all_grnd_ids[i+1:] previous_prop_ids = all_prop_ids[i+1:] grnd_mismatch = grnd_id in previous_grnd_ids and previous_prop_ids[previous_grnd_ids.index(grnd_id)] != prop_id prop_mismatch = prop_id in previous_prop_ids and previous_grnd_ids[previous_prop_ids.index(prop_id)] != grnd_id mismatch = grnd_mismatch or prop_mismatch if mismatch: mm_net += 1 # Compute and return score according to the metric track_tp_net = tp_net - mm_net track_fp_net = fp_net + mm_net track_fn_net = fn_net + mm_net if track_tp_net + (track_fp_net + track_fn_net)/2. > 0: track_score = (track_tp_net) / (track_tp_net + (track_fp_net + track_fn_net)/2.) else: track_score = 0 if change_tp_net + (change_fp_net + change_fn_net)/2. > 0: change_score = (change_tp_net) / (change_tp_net + (change_fp_net + change_fn_net)/2.) else: change_score = 0 if beta * beta * change_score + track_score > 0: combo_score = (1 + beta * beta) * (change_score * track_score) / (beta * beta * change_score + track_score) else: combo_score = 0 if verbose: print('Tracking:') print(' Mismatches: %i' % mm_net) print(' True Pos: %i' % track_tp_net) print(' False Pos: %i' % track_fp_net) print(' False Neg: %i' % track_fn_net) print(' Track Score: %.4f' % track_score) print('Change Detection:') print(' True Pos: %i' % change_tp_net) print(' False Pos: %i' % change_fp_net) print(' False Neg: %i' % change_fn_net) print(' Change Score: %.4f' % change_score) print('Combined Score: %.4f' % combo_score) if stats: return combo_score, [mm_net, track_tp_net, track_fp_net, track_fn_net, track_score, change_tp_net, change_fp_net, change_fn_net, change_score, combo_score] else: return combo_score def scot_multi_aoi(grnd_df, prop_df, threshold=0.25, base_reward=100., beta=2., stats=True, verbose=False): """ SpaceNet Change and Object Tracking (SCOT) metric, for a SpaceNet 7 submission with multiple AOIs. Input dataframes should have "aoi", "timestep", "id", & "geometry" columns. """ # Get list of AOIs from ground truth dataframe aois = sorted(list(grnd_df.aoi.drop_duplicates())) # Evaluate SCOT metric for each AOI cumulative_score = 0. all_stats = {} for i, aoi in enumerate(aois): if verbose: print() print('%i / %i: AOI %s' % (i + 1, len(aois), aoi)) grnd_df_one_aoi = grnd_df.loc[grnd_df.aoi == aoi].copy() prop_df_one_aoi = prop_df.loc[prop_df.aoi == aoi].copy() score_one_aoi, stats_one_aoi = scot_one_aoi( grnd_df_one_aoi, prop_df_one_aoi, threshold=threshold, base_reward=base_reward, beta=beta, stats=True, verbose=verbose) cumulative_score += score_one_aoi all_stats[aoi] = stats_one_aoi # Return combined SCOT metric score score = cumulative_score / len(aois) if verbose: print('Overall score: %f' % score) if stats: return score, all_stats else: return score
solaris/eval/scot.py
import geopandas as gpd import scipy.optimize import scipy.sparse def match_footprints(grnd_df, prop_df, threshold=0.25, base_reward=100.): """ Optimal matching of ground truth footprints with proposal footprints (for a single timestep). Input dataframes should have "id" & "geometry" columns. """ # Supplement IDs with indices (which run from zero # to one less than the number of unique IDs) grnd_id_set = set(grnd_df['id']) prop_id_set = set(prop_df['id']) grnd_id_to_index = {id: index for index, id in enumerate(sorted(list(grnd_id_set)))} prop_id_to_index = {id: index for index, id in enumerate(sorted(list(prop_id_set)))} grnd_index_to_id = {index: id for id, index in grnd_id_to_index.items()} prop_index_to_id = {index: id for id, index in prop_id_to_index.items()} grnd_df['index'] = grnd_df.id.apply(lambda id: grnd_id_to_index[id]) prop_df['index'] = prop_df.id.apply(lambda id: prop_id_to_index[id]) # Calculate IOU for all intersections, and the corresponding reward grnd_df['grnd_area'] = grnd_df.area prop_df['prop_area'] = prop_df.area if not (grnd_df.empty or prop_df.empty): intersect = gpd.overlay(grnd_df, prop_df) else: intersect = None if intersect is None or len(intersect) == 0: return [], [], len(grnd_df), len(prop_df), 0, len(prop_df), len(grnd_df), 0., grnd_id_set, prop_id_set intersect['inter_area'] = intersect.area intersect['iou'] = intersect['inter_area'] / (intersect['grnd_area'] + intersect['prop_area'] - intersect['inter_area']) intersect['reward'] = intersect.apply(lambda row: (row.iou > threshold) * (base_reward + row.iou), axis=1) # Convert IOUs and rewards to 2D arrays (by way of sparse matrices) iou_matrix = scipy.sparse.coo_matrix((intersect.iou, (intersect.index_1, intersect.index_2)), shape=(len(grnd_df), len(prop_df))) iou_arr = iou_matrix.toarray() reward_matrix = scipy.sparse.coo_matrix((intersect.reward, (intersect.index_1, intersect.index_2)), shape=(len(grnd_df), len(prop_df))) reward_arr = reward_matrix.toarray() # Solve unbalanced linear assignment problem grnd_match, prop_match = scipy.optimize.linear_sum_assignment(reward_arr, maximize=True) iou_match = iou_arr[grnd_match, prop_match] # Remove matches that don't actually contribute to the total score grnd_match_pruned = grnd_match[iou_match>threshold] prop_match_pruned = prop_match[iou_match>threshold] iou_match_pruned = iou_match[iou_match>threshold] # Look up IDs for each match, and calculate descriptive statistics grnd_match_ids = [grnd_index_to_id[index] for index in grnd_match_pruned] prop_match_ids = [prop_index_to_id[index] for index in prop_match_pruned] num_grnd = len(grnd_df) num_prop = len(prop_df) tp = len(iou_match_pruned) fp = num_prop - tp fn = num_grnd - tp if 2*tp + fp + fn > 0: f1 = (2*tp) / (2*tp + fp + fn) else: f1 = 0 return grnd_match_ids, prop_match_ids, num_grnd, num_prop, tp, fp, fn, f1, grnd_id_set, prop_id_set def scot_one_aoi(grnd_df, prop_df, threshold=0.25, base_reward=100., beta=2., stats=False, verbose=False): """ SpaceNet Change and Object Tracking (SCOT) metric, for one AOI. Input dataframes should have "timestep", "id", & "geometry" columns. """ # Get list of timesteps from ground truth and proposal dataframes grnd_timestep_set = set(grnd_df.timestep.drop_duplicates()) prop_timestep_set = set(grnd_df.timestep.drop_duplicates()) timesteps = sorted(list(grnd_timestep_set.union(prop_timestep_set))) # Loop through timesteps if verbose: print('Matching footprints') tp_net = 0 fp_net = 0 fn_net = 0 num_grnd_net = 0 num_prop_net = 0 all_grnd_ids = [] all_prop_ids = [] change_tp_net = 0 change_fp_net = 0 change_fn_net = 0 change_grnd_ids = set() change_prop_ids = set() for i, timestep in enumerate(timesteps): # Get just the data for this timestep grnd_df_one_timestep = grnd_df.loc[grnd_df.timestep == timestep].copy() prop_df_one_timestep = prop_df.loc[prop_df.timestep == timestep].copy() # Find footprint matches for this timestep grnd_ids, prop_ids, num_grnd, num_prop, tp, fp, fn, f1, grnd_id_set, prop_id_set = match_footprints( grnd_df_one_timestep, prop_df_one_timestep, threshold=threshold, base_reward=base_reward) # Collect aggregate statistics for tracking, and retain all match IDs tp_net += tp fp_net += fp fn_net += fn num_grnd_net += num_grnd num_prop_net += num_prop all_grnd_ids = grnd_ids + all_grnd_ids # newest first all_prop_ids = prop_ids + all_prop_ids # newest first if verbose: print(' %2i: F1 = %.4f' % (i + 1, f1)) # Collect aggregate statistics for change detection if i > 0: # Find change detection TPs, FPs, and FNs among matched footprints new_grnd = [grnd_id not in change_grnd_ids for grnd_id in grnd_ids] new_prop = [prop_id not in change_prop_ids for prop_id in prop_ids] change_tp_list = [g and p for g, p in zip(new_grnd, new_prop)] change_fp_list = [p and not g for g, p in zip(new_grnd, new_prop)] change_fn_list = [g and not p for g, p in zip(new_grnd, new_prop)] change_tp_net += sum(change_tp_list) change_fp_net += sum(change_fp_list) change_fn_net += sum(change_fn_list) # Find change detection FPs and FNs among unmatched footprints unmatched_fp = prop_id_set.difference(prop_ids).difference(change_prop_ids) unmatched_fn = grnd_id_set.difference(grnd_ids).difference(change_grnd_ids) change_fp_net += len(unmatched_fp) change_fn_net += len(unmatched_fn) change_grnd_ids = change_grnd_ids.union(grnd_id_set) change_prop_ids = change_prop_ids.union(prop_id_set) # Identify which matches are mismatches # (i.e., inconsistent with previous timesteps) if verbose: print('Identifying mismatches') mm_net = 0 for i in range(len(all_grnd_ids)): grnd_id = all_grnd_ids[i] prop_id = all_prop_ids[i] previous_grnd_ids = all_grnd_ids[i+1:] previous_prop_ids = all_prop_ids[i+1:] grnd_mismatch = grnd_id in previous_grnd_ids and previous_prop_ids[previous_grnd_ids.index(grnd_id)] != prop_id prop_mismatch = prop_id in previous_prop_ids and previous_grnd_ids[previous_prop_ids.index(prop_id)] != grnd_id mismatch = grnd_mismatch or prop_mismatch if mismatch: mm_net += 1 # Compute and return score according to the metric track_tp_net = tp_net - mm_net track_fp_net = fp_net + mm_net track_fn_net = fn_net + mm_net if track_tp_net + (track_fp_net + track_fn_net)/2. > 0: track_score = (track_tp_net) / (track_tp_net + (track_fp_net + track_fn_net)/2.) else: track_score = 0 if change_tp_net + (change_fp_net + change_fn_net)/2. > 0: change_score = (change_tp_net) / (change_tp_net + (change_fp_net + change_fn_net)/2.) else: change_score = 0 if beta * beta * change_score + track_score > 0: combo_score = (1 + beta * beta) * (change_score * track_score) / (beta * beta * change_score + track_score) else: combo_score = 0 if verbose: print('Tracking:') print(' Mismatches: %i' % mm_net) print(' True Pos: %i' % track_tp_net) print(' False Pos: %i' % track_fp_net) print(' False Neg: %i' % track_fn_net) print(' Track Score: %.4f' % track_score) print('Change Detection:') print(' True Pos: %i' % change_tp_net) print(' False Pos: %i' % change_fp_net) print(' False Neg: %i' % change_fn_net) print(' Change Score: %.4f' % change_score) print('Combined Score: %.4f' % combo_score) if stats: return combo_score, [mm_net, track_tp_net, track_fp_net, track_fn_net, track_score, change_tp_net, change_fp_net, change_fn_net, change_score, combo_score] else: return combo_score def scot_multi_aoi(grnd_df, prop_df, threshold=0.25, base_reward=100., beta=2., stats=True, verbose=False): """ SpaceNet Change and Object Tracking (SCOT) metric, for a SpaceNet 7 submission with multiple AOIs. Input dataframes should have "aoi", "timestep", "id", & "geometry" columns. """ # Get list of AOIs from ground truth dataframe aois = sorted(list(grnd_df.aoi.drop_duplicates())) # Evaluate SCOT metric for each AOI cumulative_score = 0. all_stats = {} for i, aoi in enumerate(aois): if verbose: print() print('%i / %i: AOI %s' % (i + 1, len(aois), aoi)) grnd_df_one_aoi = grnd_df.loc[grnd_df.aoi == aoi].copy() prop_df_one_aoi = prop_df.loc[prop_df.aoi == aoi].copy() score_one_aoi, stats_one_aoi = scot_one_aoi( grnd_df_one_aoi, prop_df_one_aoi, threshold=threshold, base_reward=base_reward, beta=beta, stats=True, verbose=verbose) cumulative_score += score_one_aoi all_stats[aoi] = stats_one_aoi # Return combined SCOT metric score score = cumulative_score / len(aois) if verbose: print('Overall score: %f' % score) if stats: return score, all_stats else: return score
0.559049
0.560794
from pathlib import Path import re import json from collections import defaultdict section_tex_dir = Path("tacling_climate_change_source/sections") bbl_file = Path("tacling_climate_change_source/main.bbl") sections_out = Path("section_information.json") citations_out = Path("section_citations.json") authors_out = Path("bib_authors.json") titles_out = Path("bib_titles.json") sections = {} citations = defaultdict(list) citations_lookup = set() bib_titles = {} bib_authors = {} for bibitem in bbl_file.read_text().split("\n\n")[1:-1]: bibitem = bibitem.strip().replace("\n", " ") bib_id = re.match(r"\\bibitem\{(.*?)\}", bibitem).group(1) bib_author = re.match(r"\\bibitem\{.*?\}(.*?)\\newblock", bibitem).group(1) bib_title = re.match(r".*\\newblock(.*?)\\newblock", bibitem) if bib_title: bib_title = bib_title.group(1) else: bib_title = bib_author bib_author = None # TODO: normalize tex strings (e.g. remove curly brackets and \em) bib_titles[bib_id] = bib_title bib_authors[bib_id] = bib_author authors_out.write_text(json.dumps(bib_authors, indent=4)) titles_out.write_text(json.dumps(bib_titles, indent=4)) for section_tex in section_tex_dir.glob("*.tex"): s = None ss = None sss = None p = None section_raw = section_tex.read_text() for i, line in enumerate(section_raw.split("\n")): if line.startswith("\\section{"): s = re.search(r"\\section{(.*?)\\texorpdfstring", line).group(1) s = s.strip() s = "s: " + s sections[s] = {} ss = None sss = None p = None if line.startswith("\\subsection{"): ss = re.search(r"\\subsection\*?\{(.*?)(\}|\\Gap)", line).group(1) ss = ss.strip() ss = "ss: " + ss sections[s][ss] = {} sss = None p = None if line.startswith("\\subsubsection{"): sss = re.search(r"\\subsubsection\*?\{(.*?)(\}|\\Gap)", line).group(1) sss = sss.strip() sss = "sss: " + sss sections[s][ss][sss] = {} p = None if line.startswith("\\paragraph"): p = re.search(r"\\paragraph\*?\{(.*?)\}", line).group(1) p = p.strip() p = "p: " + p if sss: sections[s][ss][sss][p] = {} elif ss: sections[s][ss][p] = {} elif s: sections[s][p] = {} # add references refs = re.findall(r"\\cite\{(.*?)\}", line) refs = ",".join(refs) refs = [r.strip() for r in refs.split(",") if r] citations_lookup.update(refs) # create section path as key if refs: k = section_tex.stem if s: k += ' | '+s if ss: k += ' | '+ss if sss: k += ' | '+sss if p: k += ' | '+p citations[k] += refs sections_out.write_text(json.dumps(sections, indent=4)) citations_out.write_text(json.dumps(citations, indent=4)) print(f"Found {len(citations_lookup)} unique citations")
parse_tex.py
from pathlib import Path import re import json from collections import defaultdict section_tex_dir = Path("tacling_climate_change_source/sections") bbl_file = Path("tacling_climate_change_source/main.bbl") sections_out = Path("section_information.json") citations_out = Path("section_citations.json") authors_out = Path("bib_authors.json") titles_out = Path("bib_titles.json") sections = {} citations = defaultdict(list) citations_lookup = set() bib_titles = {} bib_authors = {} for bibitem in bbl_file.read_text().split("\n\n")[1:-1]: bibitem = bibitem.strip().replace("\n", " ") bib_id = re.match(r"\\bibitem\{(.*?)\}", bibitem).group(1) bib_author = re.match(r"\\bibitem\{.*?\}(.*?)\\newblock", bibitem).group(1) bib_title = re.match(r".*\\newblock(.*?)\\newblock", bibitem) if bib_title: bib_title = bib_title.group(1) else: bib_title = bib_author bib_author = None # TODO: normalize tex strings (e.g. remove curly brackets and \em) bib_titles[bib_id] = bib_title bib_authors[bib_id] = bib_author authors_out.write_text(json.dumps(bib_authors, indent=4)) titles_out.write_text(json.dumps(bib_titles, indent=4)) for section_tex in section_tex_dir.glob("*.tex"): s = None ss = None sss = None p = None section_raw = section_tex.read_text() for i, line in enumerate(section_raw.split("\n")): if line.startswith("\\section{"): s = re.search(r"\\section{(.*?)\\texorpdfstring", line).group(1) s = s.strip() s = "s: " + s sections[s] = {} ss = None sss = None p = None if line.startswith("\\subsection{"): ss = re.search(r"\\subsection\*?\{(.*?)(\}|\\Gap)", line).group(1) ss = ss.strip() ss = "ss: " + ss sections[s][ss] = {} sss = None p = None if line.startswith("\\subsubsection{"): sss = re.search(r"\\subsubsection\*?\{(.*?)(\}|\\Gap)", line).group(1) sss = sss.strip() sss = "sss: " + sss sections[s][ss][sss] = {} p = None if line.startswith("\\paragraph"): p = re.search(r"\\paragraph\*?\{(.*?)\}", line).group(1) p = p.strip() p = "p: " + p if sss: sections[s][ss][sss][p] = {} elif ss: sections[s][ss][p] = {} elif s: sections[s][p] = {} # add references refs = re.findall(r"\\cite\{(.*?)\}", line) refs = ",".join(refs) refs = [r.strip() for r in refs.split(",") if r] citations_lookup.update(refs) # create section path as key if refs: k = section_tex.stem if s: k += ' | '+s if ss: k += ' | '+ss if sss: k += ' | '+sss if p: k += ' | '+p citations[k] += refs sections_out.write_text(json.dumps(sections, indent=4)) citations_out.write_text(json.dumps(citations, indent=4)) print(f"Found {len(citations_lookup)} unique citations")
0.150778
0.124372
from __future__ import unicode_literals from django.db import migrations current_montage = [ "SC-2078", "SC-2197", "SC-2190", "SC-2189", "SC-2298", "SC-2059", "SC-2058", "SC-2299", "SC-2163", "SC-2162", "SC-2284", "SC-2043", "SC-1196", "SC-2161", "SC-2160", "SC-2149", "SC-2148", "SC-1188", "SC-2035", "SC-2034", "SC-2036", "SC-2277", "SC-1189", "SC-2153", "SC-2150", "SC-2017", "SC-2018", "SC-2259", "SC-2144", "SC-2023", "SC-2265", "SC-2147", "SC-2266", "SC-2263", "SC-2140", "SC-2264", "SC-2022", "SC-2249", "SC-1039", "SC-2369", "SC-2257", "SC-2254", "SC-2015", "SC-2255", "SC-1162", "SC-2252", "SC-1161", "SC-2253", "SC-2250", "SC-2371", "SC-2493", "SC-1163", "SC-2490", "SC-2370", "SC-2491", "SC-1389", "SC-1397", "SC-2002", "SC-2123", "SC-2488", "SC-2001", "SC-2004", "SC-1399", "SC-2486", "SC-2484", "SC-1392", "SC-1395", "SC-2481", "SC-2000", "SC-1391", "SC-1819", "SC-1937", "SC-1936", "SC-1818", "SC-1812", "SC-1811", "SC-1935", "SC-1813", "SC-1810", "SC-1930", "SC-1809", "SC-1808", "SC-1805", "SC-1804", "SC-1807", "SC-1806", "SC-1801", "SC-1800", "SC-1803", "SC-1802", "SC-1915", "SC-1904", "SC-1903", "SC-9999", "SCdna-2", "SC-2099", "SC-2506", "SC-1658", "SC-1537", "SC-1415", "SC-1418", "SC-1539", "SC-2504", "SC-2505", "SC-1417", "SC-1533", "SC-1654", "SC-1535", "SC-1898", "SC-1413", "SC-1660", "SC-1784", "SC-1300", "SC-1421", "SC-1409", "SC-1529", "SC-1405", "SC-1889", "SC-1888", "SC-1646", "SC-1525", "SC-1527", "SC-1648", "SC-1401", "SC-1521", "SC-1642", "SC-1884", "SC-1403", "SC-1644", "SC-1523", "SC-1650", "SC-1892", "SC-1891", "SC-1531", "SC-1894", "SC-1652", "SC-1893", "SC-1890", "SC-1519", "SC-1999", "SC-1636", "SC-1877", "SC-1514", "SC-1998", "SC-1517", "SC-1638", "SC-1879", "SC-1516", "SC-1511", "SC-1995", "SC-1994", "SC-1997", "SC-1996", "SC-1512", "SC-1881", "SC-1880", "SC-2573", "SC-1883", "SC-1640", "SC-1882", "SC-1507", "SC-1509", "SC-1625", "SC-1988", "SC-1867", "SC-1866", "SC-1503", "SC-1627", "SC-1989", "SC-1505", "SC-1868", "SC-1621", "SC-1863", "SC-1984", "SC-1623", "SC-1501", "SC-1991", "SC-1990", "SC-1993", "SC-1992", "SC-1617", "SC-1619", "SC-1977", "SC-1976", "SC-1978", "SC-1973", "SC-1974", "SC-2531", "SC-930 ", "SC-1728", "SC-1727", "SC-1729", "SC-1845", "SC-1965", "SC-1844", "SC-1967", "SC-1841", "SC-1962", "SC-1840", "SC-1601", "SC-1963", "SC-1842", "SC-1838", "SC-1837", "SC-1839", "SC-1836", "SC-1711", "SC-1944", "SC-1823", "SC-1943", "SC-1701", "SC-1822", "SC-1824", "SC-1945", "SC-1942", "SC-1941", "SC-2109", "SC-2229", "SC-2469", "SC-1378", "SC-2228", "SC-2104", "SC-1499", "SC-2468", "SC-1385", "SC-2474", "SC-1387", "SC-1382", "SC-2230", "SC-1384", "SC-1380", "SC-2219", "SC-1489", "SC-2216", "SC-1368", "SC-2457", "SC-1374", "SC-1495", "SC-2100", "SC-1135", "SC-1134", "SC-1497", "SC-1376", "SC-1492", "SC-1370", "SC-1372", "SC-1493", "SC-1599", "SC-1357", "SC-1477", "SC-1359", "SC-2203", "SC-1358", "SC-2204", "SC-1479", "SC-1485", "SC-1364", "SC-2573", "SC-2331", "SC-1366", "SC-1487", "SC-1360", "SC-1481", "SC-2330", "SC-1362", "SC-1483", "SC-1482", "SC-2319", "SC-1467", "SC-2557", "SC-1587", "SC-1345", "SC-1469", "SC-1348", "SC-1589", "SC-1347", "SC-2556", "SC-2201", "SC-1353", "SC-1595", "SC-2202", "SC-1473", "SC-1352", "SC-1597", "SC-2320", "SC-1234", "SC-1355", "SC-1475", "SC-2321", "SC-2200", "SC-1354", "SC-2560", "SC-1591", "SC-2561", "SC-1593", "SC-1471", "SC-1350", "SC-1339", "SC-2308", "SC-2309", "SC-1459", "SC-1577", "SC-1335", "SC-1455", "SC-1697", "SC-1579", "SC-1457", "SC-2311", "SC-1342", "SC-2553", "SC-1341", "SC-2312", "SC-1583", "SC-1465", "SC-2310", "SC-2552", "SC-1343", "SC-1585", "SC-1581", "SC-1448", "SC-1569", "SC-1687", "SC-2535", "SC-1565", "SC-1444", "SC-2533", "SC-1446", "SC-1688", "SC-1567", "SC-2534", "SC-1573", "SC-1452", "SC-1696", "SC-1575", "SC-1454", "SC-1695", "SC-1571", "SC-1450", "SC-1559", "SC-1437", "SC-1439", "SC-1555", "SC-1797", "SC-1796", "SC-1678", "SC-1557", "SC-1799", "SC-1798", "SC-1435", "SC-2531", "SC-1441", "SC-1561", "SC-2532", "SC-1443", "SC-1563", "SC-2517", "SC-1668", "SC-1789", "SC-2515", "SC-1429", "SC-2516", "SC-1307", "SC-2513", "SC-1423", "SC-2514", "SC-1425", "SC-2511", "SC-2512", "SC-2520", "SC-1792", "SC-1550", "SC-1553", "SC-1795", "SC-1794" ] def update_montage_status(apps, schema_editor): Analysis = apps.get_model('sisyphus', 'dlpanalysisinformation') for a in Analysis.objects.all(): if a.analysis_jira_ticket in current_montage: print("UDPATING ", a, " TO SUCCESS") a.montage_status = "Success" else: print("UDPATING ", a, " TO IGNORE") a.montage_status = "Ignore" a.save() class Migration(migrations.Migration): dependencies = [ ('sisyphus', '0002_auto_20190809_1118'), ] operations = [ migrations.RunPython(update_montage_status) ]
sisyphus/migrations/0003_auto_20190809_1123.py
from __future__ import unicode_literals from django.db import migrations current_montage = [ "SC-2078", "SC-2197", "SC-2190", "SC-2189", "SC-2298", "SC-2059", "SC-2058", "SC-2299", "SC-2163", "SC-2162", "SC-2284", "SC-2043", "SC-1196", "SC-2161", "SC-2160", "SC-2149", "SC-2148", "SC-1188", "SC-2035", "SC-2034", "SC-2036", "SC-2277", "SC-1189", "SC-2153", "SC-2150", "SC-2017", "SC-2018", "SC-2259", "SC-2144", "SC-2023", "SC-2265", "SC-2147", "SC-2266", "SC-2263", "SC-2140", "SC-2264", "SC-2022", "SC-2249", "SC-1039", "SC-2369", "SC-2257", "SC-2254", "SC-2015", "SC-2255", "SC-1162", "SC-2252", "SC-1161", "SC-2253", "SC-2250", "SC-2371", "SC-2493", "SC-1163", "SC-2490", "SC-2370", "SC-2491", "SC-1389", "SC-1397", "SC-2002", "SC-2123", "SC-2488", "SC-2001", "SC-2004", "SC-1399", "SC-2486", "SC-2484", "SC-1392", "SC-1395", "SC-2481", "SC-2000", "SC-1391", "SC-1819", "SC-1937", "SC-1936", "SC-1818", "SC-1812", "SC-1811", "SC-1935", "SC-1813", "SC-1810", "SC-1930", "SC-1809", "SC-1808", "SC-1805", "SC-1804", "SC-1807", "SC-1806", "SC-1801", "SC-1800", "SC-1803", "SC-1802", "SC-1915", "SC-1904", "SC-1903", "SC-9999", "SCdna-2", "SC-2099", "SC-2506", "SC-1658", "SC-1537", "SC-1415", "SC-1418", "SC-1539", "SC-2504", "SC-2505", "SC-1417", "SC-1533", "SC-1654", "SC-1535", "SC-1898", "SC-1413", "SC-1660", "SC-1784", "SC-1300", "SC-1421", "SC-1409", "SC-1529", "SC-1405", "SC-1889", "SC-1888", "SC-1646", "SC-1525", "SC-1527", "SC-1648", "SC-1401", "SC-1521", "SC-1642", "SC-1884", "SC-1403", "SC-1644", "SC-1523", "SC-1650", "SC-1892", "SC-1891", "SC-1531", "SC-1894", "SC-1652", "SC-1893", "SC-1890", "SC-1519", "SC-1999", "SC-1636", "SC-1877", "SC-1514", "SC-1998", "SC-1517", "SC-1638", "SC-1879", "SC-1516", "SC-1511", "SC-1995", "SC-1994", "SC-1997", "SC-1996", "SC-1512", "SC-1881", "SC-1880", "SC-2573", "SC-1883", "SC-1640", "SC-1882", "SC-1507", "SC-1509", "SC-1625", "SC-1988", "SC-1867", "SC-1866", "SC-1503", "SC-1627", "SC-1989", "SC-1505", "SC-1868", "SC-1621", "SC-1863", "SC-1984", "SC-1623", "SC-1501", "SC-1991", "SC-1990", "SC-1993", "SC-1992", "SC-1617", "SC-1619", "SC-1977", "SC-1976", "SC-1978", "SC-1973", "SC-1974", "SC-2531", "SC-930 ", "SC-1728", "SC-1727", "SC-1729", "SC-1845", "SC-1965", "SC-1844", "SC-1967", "SC-1841", "SC-1962", "SC-1840", "SC-1601", "SC-1963", "SC-1842", "SC-1838", "SC-1837", "SC-1839", "SC-1836", "SC-1711", "SC-1944", "SC-1823", "SC-1943", "SC-1701", "SC-1822", "SC-1824", "SC-1945", "SC-1942", "SC-1941", "SC-2109", "SC-2229", "SC-2469", "SC-1378", "SC-2228", "SC-2104", "SC-1499", "SC-2468", "SC-1385", "SC-2474", "SC-1387", "SC-1382", "SC-2230", "SC-1384", "SC-1380", "SC-2219", "SC-1489", "SC-2216", "SC-1368", "SC-2457", "SC-1374", "SC-1495", "SC-2100", "SC-1135", "SC-1134", "SC-1497", "SC-1376", "SC-1492", "SC-1370", "SC-1372", "SC-1493", "SC-1599", "SC-1357", "SC-1477", "SC-1359", "SC-2203", "SC-1358", "SC-2204", "SC-1479", "SC-1485", "SC-1364", "SC-2573", "SC-2331", "SC-1366", "SC-1487", "SC-1360", "SC-1481", "SC-2330", "SC-1362", "SC-1483", "SC-1482", "SC-2319", "SC-1467", "SC-2557", "SC-1587", "SC-1345", "SC-1469", "SC-1348", "SC-1589", "SC-1347", "SC-2556", "SC-2201", "SC-1353", "SC-1595", "SC-2202", "SC-1473", "SC-1352", "SC-1597", "SC-2320", "SC-1234", "SC-1355", "SC-1475", "SC-2321", "SC-2200", "SC-1354", "SC-2560", "SC-1591", "SC-2561", "SC-1593", "SC-1471", "SC-1350", "SC-1339", "SC-2308", "SC-2309", "SC-1459", "SC-1577", "SC-1335", "SC-1455", "SC-1697", "SC-1579", "SC-1457", "SC-2311", "SC-1342", "SC-2553", "SC-1341", "SC-2312", "SC-1583", "SC-1465", "SC-2310", "SC-2552", "SC-1343", "SC-1585", "SC-1581", "SC-1448", "SC-1569", "SC-1687", "SC-2535", "SC-1565", "SC-1444", "SC-2533", "SC-1446", "SC-1688", "SC-1567", "SC-2534", "SC-1573", "SC-1452", "SC-1696", "SC-1575", "SC-1454", "SC-1695", "SC-1571", "SC-1450", "SC-1559", "SC-1437", "SC-1439", "SC-1555", "SC-1797", "SC-1796", "SC-1678", "SC-1557", "SC-1799", "SC-1798", "SC-1435", "SC-2531", "SC-1441", "SC-1561", "SC-2532", "SC-1443", "SC-1563", "SC-2517", "SC-1668", "SC-1789", "SC-2515", "SC-1429", "SC-2516", "SC-1307", "SC-2513", "SC-1423", "SC-2514", "SC-1425", "SC-2511", "SC-2512", "SC-2520", "SC-1792", "SC-1550", "SC-1553", "SC-1795", "SC-1794" ] def update_montage_status(apps, schema_editor): Analysis = apps.get_model('sisyphus', 'dlpanalysisinformation') for a in Analysis.objects.all(): if a.analysis_jira_ticket in current_montage: print("UDPATING ", a, " TO SUCCESS") a.montage_status = "Success" else: print("UDPATING ", a, " TO IGNORE") a.montage_status = "Ignore" a.save() class Migration(migrations.Migration): dependencies = [ ('sisyphus', '0002_auto_20190809_1118'), ] operations = [ migrations.RunPython(update_montage_status) ]
0.400984
0.29015
# IMPORT from abc import ABCMeta from abc import abstractmethod from concurrent.futures import ThreadPoolExecutor from bluepy.btle import BTLEException from blue_st_sdk.utils.ble_node_definitions import Debug from blue_st_sdk.utils.python_utils import lock # CLASSES class DebugConsole(): """Class used to read/write debug messages.""" _MAXIMUM_MESSAGE_SIZE_BYTES = 20 """Maximum size of the messages to send.""" _NUMBER_OF_THREADS = 5 """Number of threads to be used to notify the listeners.""" def __init__(self, node, stdinout_characteristic, stderr_characteristic): """Constructor. Args: node (:class:`blue_st_sdk.node.Node`): Node that will send the data. stdinout_characteristic (Characteristic): The BLE characteristic used to read/write data from/to stdin/stdout. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. stderr_characteristic (Characteristic): The BLE characteristic used to read data from stderr. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. """ self._node = node """Node that sends data to this class.""" self._stdinout_characteristic = stdinout_characteristic """Characteristic used to read/write data from/to stdin/stdout.""" self._stderr_characteristic = stderr_characteristic """Characteristic used to read data from stderr.""" self._thread_pool = ThreadPoolExecutor(DebugConsole._NUMBER_OF_THREADS) """Pool of thread used to notify the listeners.""" self._listeners = [] """List of listeners to the events of new data received. It is a thread safe list, so a listener can subscribe itself through a callback.""" def _decode_data(self, data): """Convert data to standard ascii characters. Args: data (bytearray): Data to be encoded. Returns: str: A string representing the given data. """ return data.decode('ISO-8859-1') def write(self, data): """Write an array of bytes to the stdin. The message might be sent through more iterations on the Bluetooth channel. Args: data (bytearray): Data to be sent. Returns: int: The number of bytes sent to the stdin/stdout standard characteristic. """ try: char_handle = self._stdinout_characteristic.getHandle() bytes_sent = 0 while bytes_sent < len(data): # Computing data to send. bytes_to_send = min( self._MAXIMUM_MESSAGE_SIZE_BYTES, len(data) - bytes_sent ) data_to_send = data[bytes_sent:bytes_sent + bytes_to_send] # Writing data. self._node.writeCharacteristic( char_handle, data_to_send, True) bytes_sent += bytes_to_send # Calling on-write callback for a debug characteristic. self.on_write_characteristic( self._stdinout_characteristic, data_to_send, True) return bytes_sent except BTLEException as e: self._node._unexpected_disconnect() def add_listener(self, listener): """Adding a listener. Args: listener (:class:`blue_st_sdk.debug.DebugListener`): Listener to be added. """ if listener is not None: with lock(self): if not listener in self._listeners: self._listeners.append(listener) if self._listeners: self._node.set_notification_status( self._stdinout_characteristic, True) self._node.set_notification_status( self._stderr_characteristic, True) def remove_listener(self, listener): """Remove a listener. Args: listener (:class:`blue_st_sdk.debug.DebugListener`): Listener to be removed. """ if listener is not None: with lock(self): if listener in self._listeners: self._listeners.remove(listener) if not self._listeners: self._node.set_notification_status( self._stdinout_characteristic, False) self._node.set_notification_status( self._stderr_characteristic, False) def on_update_characteristic(self, characteristic, data): """The characteristic has been updated. If it is a debug characteristic, data are sent to the registered listeners. Args: characteristic (Characteristic): The BLE characteristic that has been updated. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. data (str): The data notified from the given characteristic. """ try: if len(self._listeners) == 0: return data_str = self._decode_data(data) if characteristic.uuid == \ Debug.DEBUG_STDINOUT_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stdout_receive( self, data_str)) elif characteristic.uuid == \ Debug.DEBUG_STDERR_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stderr_receive( self, data_str)) except BTLEException as e: self._node._unexpected_disconnect() def on_write_characteristic(self, characteristic, data, status): """The characteristic has been written. Args: characteristic (Characteristic): The BLE characteristic that has been written. data (bytearray): Received data. status (bool): True if the writing operation was successfully, False otherwise. """ try: if len(self._listeners) == 0: return data_str = self._decode_data(data) if characteristic.uuid == \ Debug.DEBUG_STDINOUT_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stdin_send( self, data_str[0:self._MAXIMUM_MESSAGE_SIZE_BYTES], status)) except BTLEException as e: self._node._unexpected_disconnect() def get_node(self): """Getting the node that listen to / write to this debug console. Returns: node (:class:`blue_st_sdk.node.Node`): the node that listen/write to this debug console. """ return self._node class DebugConsoleListener(object): """Interface used by the :class:`blue_st_sdk.debug.DebugConsole` class to notify changes on a debug console. Data received/sent from/to a node are encoded with ISO-8859-1 charset. """ __metaclass__ = ABCMeta @abstractmethod def on_stdout_receive(self, debug_console, message): """Called whenever a new message is received on the standard output. Args: debug_console (object): Console that sends the message. message (str): The message received on the stdout console. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stdut_received()" to use the "DebugListener"' 'class.') @abstractmethod def on_stderr_receive(self, debug_console, message): """Called whenever a new message is received on the standard error. Args: debug_console (object): Console that sends the message. message (str): The message received on the stderr console. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stderr_receive()" to use the "DebugListener"' 'class.') @abstractmethod def on_stdin_send(self, debug_console, message, status): """Called whenever a new message is sent to the standard input. Args: debug_console (object): Console that receives the message. message (str): The message sent to the stdin console. status (bool): True if the message is sent correctly, False otherwise. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stdin_send()" to use the "DebugListener"' 'class.')
blue_st_sdk/debug_console.py
# IMPORT from abc import ABCMeta from abc import abstractmethod from concurrent.futures import ThreadPoolExecutor from bluepy.btle import BTLEException from blue_st_sdk.utils.ble_node_definitions import Debug from blue_st_sdk.utils.python_utils import lock # CLASSES class DebugConsole(): """Class used to read/write debug messages.""" _MAXIMUM_MESSAGE_SIZE_BYTES = 20 """Maximum size of the messages to send.""" _NUMBER_OF_THREADS = 5 """Number of threads to be used to notify the listeners.""" def __init__(self, node, stdinout_characteristic, stderr_characteristic): """Constructor. Args: node (:class:`blue_st_sdk.node.Node`): Node that will send the data. stdinout_characteristic (Characteristic): The BLE characteristic used to read/write data from/to stdin/stdout. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. stderr_characteristic (Characteristic): The BLE characteristic used to read data from stderr. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. """ self._node = node """Node that sends data to this class.""" self._stdinout_characteristic = stdinout_characteristic """Characteristic used to read/write data from/to stdin/stdout.""" self._stderr_characteristic = stderr_characteristic """Characteristic used to read data from stderr.""" self._thread_pool = ThreadPoolExecutor(DebugConsole._NUMBER_OF_THREADS) """Pool of thread used to notify the listeners.""" self._listeners = [] """List of listeners to the events of new data received. It is a thread safe list, so a listener can subscribe itself through a callback.""" def _decode_data(self, data): """Convert data to standard ascii characters. Args: data (bytearray): Data to be encoded. Returns: str: A string representing the given data. """ return data.decode('ISO-8859-1') def write(self, data): """Write an array of bytes to the stdin. The message might be sent through more iterations on the Bluetooth channel. Args: data (bytearray): Data to be sent. Returns: int: The number of bytes sent to the stdin/stdout standard characteristic. """ try: char_handle = self._stdinout_characteristic.getHandle() bytes_sent = 0 while bytes_sent < len(data): # Computing data to send. bytes_to_send = min( self._MAXIMUM_MESSAGE_SIZE_BYTES, len(data) - bytes_sent ) data_to_send = data[bytes_sent:bytes_sent + bytes_to_send] # Writing data. self._node.writeCharacteristic( char_handle, data_to_send, True) bytes_sent += bytes_to_send # Calling on-write callback for a debug characteristic. self.on_write_characteristic( self._stdinout_characteristic, data_to_send, True) return bytes_sent except BTLEException as e: self._node._unexpected_disconnect() def add_listener(self, listener): """Adding a listener. Args: listener (:class:`blue_st_sdk.debug.DebugListener`): Listener to be added. """ if listener is not None: with lock(self): if not listener in self._listeners: self._listeners.append(listener) if self._listeners: self._node.set_notification_status( self._stdinout_characteristic, True) self._node.set_notification_status( self._stderr_characteristic, True) def remove_listener(self, listener): """Remove a listener. Args: listener (:class:`blue_st_sdk.debug.DebugListener`): Listener to be removed. """ if listener is not None: with lock(self): if listener in self._listeners: self._listeners.remove(listener) if not self._listeners: self._node.set_notification_status( self._stdinout_characteristic, False) self._node.set_notification_status( self._stderr_characteristic, False) def on_update_characteristic(self, characteristic, data): """The characteristic has been updated. If it is a debug characteristic, data are sent to the registered listeners. Args: characteristic (Characteristic): The BLE characteristic that has been updated. Refer to `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_ for more information. data (str): The data notified from the given characteristic. """ try: if len(self._listeners) == 0: return data_str = self._decode_data(data) if characteristic.uuid == \ Debug.DEBUG_STDINOUT_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stdout_receive( self, data_str)) elif characteristic.uuid == \ Debug.DEBUG_STDERR_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stderr_receive( self, data_str)) except BTLEException as e: self._node._unexpected_disconnect() def on_write_characteristic(self, characteristic, data, status): """The characteristic has been written. Args: characteristic (Characteristic): The BLE characteristic that has been written. data (bytearray): Received data. status (bool): True if the writing operation was successfully, False otherwise. """ try: if len(self._listeners) == 0: return data_str = self._decode_data(data) if characteristic.uuid == \ Debug.DEBUG_STDINOUT_BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stdin_send( self, data_str[0:self._MAXIMUM_MESSAGE_SIZE_BYTES], status)) except BTLEException as e: self._node._unexpected_disconnect() def get_node(self): """Getting the node that listen to / write to this debug console. Returns: node (:class:`blue_st_sdk.node.Node`): the node that listen/write to this debug console. """ return self._node class DebugConsoleListener(object): """Interface used by the :class:`blue_st_sdk.debug.DebugConsole` class to notify changes on a debug console. Data received/sent from/to a node are encoded with ISO-8859-1 charset. """ __metaclass__ = ABCMeta @abstractmethod def on_stdout_receive(self, debug_console, message): """Called whenever a new message is received on the standard output. Args: debug_console (object): Console that sends the message. message (str): The message received on the stdout console. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stdut_received()" to use the "DebugListener"' 'class.') @abstractmethod def on_stderr_receive(self, debug_console, message): """Called whenever a new message is received on the standard error. Args: debug_console (object): Console that sends the message. message (str): The message received on the stderr console. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stderr_receive()" to use the "DebugListener"' 'class.') @abstractmethod def on_stdin_send(self, debug_console, message, status): """Called whenever a new message is sent to the standard input. Args: debug_console (object): Console that receives the message. message (str): The message sent to the stdin console. status (bool): True if the message is sent correctly, False otherwise. Raises: :exc:`NotImplementedError` if the method has not been implemented. """ raise NotImplementedError( 'You must implement "on_stdin_send()" to use the "DebugListener"' 'class.')
0.769946
0.191725
__author__ = "<NAME>" __copyright__ = "Copyright (c) 2021 <NAME> All Rights Reserved." __email__ = "<EMAIL>" __license__ = "Apache 2" import copy import json from pprint import pprint import requests DATASETS_URL = "https://phenotypes.healthdatagateway.org/api/v1/data-sources/?format=json" PHENOTYPES_URL = "https://phenotypes.healthdatagateway.org/api/v1/public/phenotypes/?format=json" PHENOTYPE_LIB_URL = "https://phenotypes.healthdatagateway.org/phenotypes/{phenotype_id}/version/{version}/detail/#home" DATA_SOURCE_FIXES = { 3: { "id": 3, "name": "Civil Registration - Deaths", "pid": "050163dc-1728-4ac5-a7d9-4dd3ca0ca12a", "url": "https://web.www.healthdatagateway.org/dataset/050163dc-1728-4ac5-a7d9-4dd3ca0ca12a" }, 17: { "id": 17, "name": "General Acute Inpatient and Day Case - Scottish Morbidity Record (SMR01)", "pid": "98cda353-0011-45b2-80ca-4ed24cd084bf", "url": "https://web.www.healthdatagateway.org/dataset/98cda353-0011-45b2-80ca-4ed24cd084bf" }, 19: { "id": 19, "name": "Death Registration Data - Provisional Monthly Extracts", "pid": "487222b7-5c13-4a92-8b41-044796048720", "url": "https://web.www.healthdatagateway.org/dataset/487222b7-5c13-4a92-8b41-044796048720" }, 21: { "id": 21, "name": "Hospitalised patients with diabetic emergencies & acute diabetic health concerns", "pid": "0d556d7e-be27-4979-a09e-d419b2e838f3", "url": "https://web.www.healthdatagateway.org/dataset/0d556d7e-be27-4979-a09e-d419b2e838f3" }, 22: { "id": 22, "name": "Hospitalised patients with diabetic emergencies & acute diabetic health concerns", "pid": "0d556d7e-be27-4979-a09e-d419b2e838f3", "url": "https://web.www.healthdatagateway.org/dataset/0d556d7e-be27-4979-a09e-d419b2e838f3" } } def request_url(URL): """HTTP GET request and load into json""" print(URL) r = requests.get(URL) if r.status_code != requests.codes.ok: r.raise_for_status() return json.loads(r.text) def write_json(data, filename=None, indent=2): with (open(filename, 'w') if filename else sys.stdout) as file: json.dump(data, file, indent=indent) def get_datasets(): DATASETS = {} datasets = request_url(DATASETS_URL) for d in datasets: dataset = { 'id': d['id'], 'name': d['name'], 'pid': d['uid'], 'url': d['url'], } if d['uid'] != "": DATASETS[d['id']] = dataset DATASETS.update(DATA_SOURCE_FIXES) return DATASETS def get_phenotypes(datasets): PHENOTYPES = [] phenotypes = request_url(PHENOTYPES_URL) for p in phenotypes: if len(p['data_sources']): phenotype = { "id": p['phenotype_id'], "name": p['phenotype_name'], "type": p['type'], } latest_version = [v['version_id'] for v in p['versions'] if v['is_latest'] == True] if len(latest_version): phenotype['url'] = PHENOTYPE_LIB_URL.format(phenotype_id=p['phenotype_id'], version=latest_version[0]) data_sources = [datasets[ds['id']] for ds in p['data_sources'] if ds['id'] in datasets.keys()] phenotype['datasets'] = data_sources PHENOTYPES.append(phenotype) return PHENOTYPES def datasets2phenotypes(phenotypes): DATASETS = {} for p in phenotypes: temp = copy.deepcopy(p) del temp['datasets'] for d in p['datasets']: DATASETS.setdefault(d['pid'], []) DATASETS[d['pid']].append(temp) return DATASETS def main(): datasets = get_datasets() phenotypes = get_phenotypes(datasets) d2p = datasets2phenotypes(phenotypes) write_json(d2p, "_data/dataset2phenotypes.json") if __name__ == '__main__': main()
scripts/generate_crossrefs.py
__author__ = "<NAME>" __copyright__ = "Copyright (c) 2021 <NAME> All Rights Reserved." __email__ = "<EMAIL>" __license__ = "Apache 2" import copy import json from pprint import pprint import requests DATASETS_URL = "https://phenotypes.healthdatagateway.org/api/v1/data-sources/?format=json" PHENOTYPES_URL = "https://phenotypes.healthdatagateway.org/api/v1/public/phenotypes/?format=json" PHENOTYPE_LIB_URL = "https://phenotypes.healthdatagateway.org/phenotypes/{phenotype_id}/version/{version}/detail/#home" DATA_SOURCE_FIXES = { 3: { "id": 3, "name": "Civil Registration - Deaths", "pid": "050163dc-1728-4ac5-a7d9-4dd3ca0ca12a", "url": "https://web.www.healthdatagateway.org/dataset/050163dc-1728-4ac5-a7d9-4dd3ca0ca12a" }, 17: { "id": 17, "name": "General Acute Inpatient and Day Case - Scottish Morbidity Record (SMR01)", "pid": "98cda353-0011-45b2-80ca-4ed24cd084bf", "url": "https://web.www.healthdatagateway.org/dataset/98cda353-0011-45b2-80ca-4ed24cd084bf" }, 19: { "id": 19, "name": "Death Registration Data - Provisional Monthly Extracts", "pid": "487222b7-5c13-4a92-8b41-044796048720", "url": "https://web.www.healthdatagateway.org/dataset/487222b7-5c13-4a92-8b41-044796048720" }, 21: { "id": 21, "name": "Hospitalised patients with diabetic emergencies & acute diabetic health concerns", "pid": "0d556d7e-be27-4979-a09e-d419b2e838f3", "url": "https://web.www.healthdatagateway.org/dataset/0d556d7e-be27-4979-a09e-d419b2e838f3" }, 22: { "id": 22, "name": "Hospitalised patients with diabetic emergencies & acute diabetic health concerns", "pid": "0d556d7e-be27-4979-a09e-d419b2e838f3", "url": "https://web.www.healthdatagateway.org/dataset/0d556d7e-be27-4979-a09e-d419b2e838f3" } } def request_url(URL): """HTTP GET request and load into json""" print(URL) r = requests.get(URL) if r.status_code != requests.codes.ok: r.raise_for_status() return json.loads(r.text) def write_json(data, filename=None, indent=2): with (open(filename, 'w') if filename else sys.stdout) as file: json.dump(data, file, indent=indent) def get_datasets(): DATASETS = {} datasets = request_url(DATASETS_URL) for d in datasets: dataset = { 'id': d['id'], 'name': d['name'], 'pid': d['uid'], 'url': d['url'], } if d['uid'] != "": DATASETS[d['id']] = dataset DATASETS.update(DATA_SOURCE_FIXES) return DATASETS def get_phenotypes(datasets): PHENOTYPES = [] phenotypes = request_url(PHENOTYPES_URL) for p in phenotypes: if len(p['data_sources']): phenotype = { "id": p['phenotype_id'], "name": p['phenotype_name'], "type": p['type'], } latest_version = [v['version_id'] for v in p['versions'] if v['is_latest'] == True] if len(latest_version): phenotype['url'] = PHENOTYPE_LIB_URL.format(phenotype_id=p['phenotype_id'], version=latest_version[0]) data_sources = [datasets[ds['id']] for ds in p['data_sources'] if ds['id'] in datasets.keys()] phenotype['datasets'] = data_sources PHENOTYPES.append(phenotype) return PHENOTYPES def datasets2phenotypes(phenotypes): DATASETS = {} for p in phenotypes: temp = copy.deepcopy(p) del temp['datasets'] for d in p['datasets']: DATASETS.setdefault(d['pid'], []) DATASETS[d['pid']].append(temp) return DATASETS def main(): datasets = get_datasets() phenotypes = get_phenotypes(datasets) d2p = datasets2phenotypes(phenotypes) write_json(d2p, "_data/dataset2phenotypes.json") if __name__ == '__main__': main()
0.311532
0.201322
import weakref from nfv_common import debug from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT DLOG = debug.debug_get_logger('nfv_common.strategy.step') class StrategyStep(object): """ Strategy Step """ def __init__(self, name, force_pass=False, timeout_in_secs=0, max_retries=1): self._id = 0 self._name = name self._force_pass = force_pass self._timeout_in_secs = timeout_in_secs self._max_retries = max_retries self._result = STRATEGY_STEP_RESULT.INITIAL self._result_reason = '' self._stage_reference = None self._start_date_time = '' self._end_date_time = '' @property def name(self): """ Returns the name of the step """ return self._name @property def id(self): """ Returns the id of the step """ return self._id @id.setter def id(self, value): """ Sets the id of the step """ self._id = value @property def force_pass(self): """ Returns the true if force_pass has been set, otherwise false """ return self._force_pass @property def max_retries(self): """ Returns the maximum retry attempts for step to be completed """ return self._max_retries @property def timeout_in_secs(self): """ Returns the maximum amount of time to wait for completion """ return self._timeout_in_secs @property def result(self): """ Returns the result of the step """ return self._result @result.setter def result(self, result): """ Updates the result of the step """ self._result = result @property def result_reason(self): """ Returns the reason for the result of the step """ return self._result_reason @result_reason.setter def result_reason(self, reason): """ Updates the reason for the result of the step """ self._result_reason = reason @property def start_date_time(self): """ Returns the start date-time of the step """ return self._start_date_time @start_date_time.setter def start_date_time(self, date_time_str): """ Updates the start date-time of the step """ self._start_date_time = date_time_str @property def end_date_time(self): """ Returns the end date-time of the step """ return self._end_date_time @end_date_time.setter def end_date_time(self, date_time_str): """ Updates the end date-time of the step """ self._end_date_time = date_time_str @property def strategy(self): """ Returns the strategy this step is a member of """ if self.phase is not None: return self.phase.strategy return None @property def phase(self): """ Returns the phase this step is a member of """ if self.stage is not None: return self.stage.phase return None @property def stage(self): """ Returns the stage this step is a member of """ if self._stage_reference is not None: return self._stage_reference() return None @stage.setter def stage(self, stage_value): """ Set the stage that this step is a member of """ self._stage_reference = weakref.ref(stage_value) def extend_timeout(self, timeout_in_secs): """ Allow the step timeout to be extended """ DLOG.verbose("Extending strategy step timeout for %s to %s." % (self._name, timeout_in_secs)) self._timeout_in_secs = timeout_in_secs if self._stage_reference is not None: self.stage.step_extend_timeout() def abort(self): """ Strategy Step Abort (can be overridden by child class) """ DLOG.info("Default strategy step abort for %s." % self._name) return [] def apply(self): """ Strategy Step Apply (expected to be overridden by child class) """ DLOG.verbose("Default strategy step apply for %s." % self._name) return STRATEGY_STEP_RESULT.SUCCESS, '' def complete(self, result, result_reason): """ Strategy Step Completed (can be overridden by child class) """ DLOG.verbose("Default strategy step complete for %s, result=%s, " "reason=%s." % (self._name, result, result_reason)) return result, result_reason def timeout(self): """ Strategy Step Timeout (can be overridden by child class) """ DLOG.verbose("Default strategy step timeout for %s, timeout=%s secs." % (self._name, self._timeout_in_secs)) return STRATEGY_STEP_RESULT.TIMED_OUT, '' def handle_event(self, event, event_data=None): """ Strategy Step Handle Event (expected to be overridden by child class) """ DLOG.verbose("Default strategy step handle event for %s." % self._name) return False def from_dict(self, data): """ Returns a strategy step object initialized using the given dictionary """ StrategyStep.__init__(self, data['name'], data['force_pass'], data['timeout'], data['max_retries']) self._result = data['result'] self._result_reason = data['result_reason'] self._start_date_time = data['start_date_time'] self._end_date_time = data['end_date_time'] return self def as_dict(self): """ Represent the strategy step as a dictionary """ data = dict() data['id'] = self._id data['name'] = self._name data['force_pass'] = self._force_pass data['timeout'] = self._timeout_in_secs data['max_retries'] = self._max_retries data['result'] = self._result data['result_reason'] = self._result_reason data['start_date_time'] = self._start_date_time data['end_date_time'] = self._end_date_time return data
nfv/nfv-common/nfv_common/strategy/_strategy_step.py
import weakref from nfv_common import debug from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT DLOG = debug.debug_get_logger('nfv_common.strategy.step') class StrategyStep(object): """ Strategy Step """ def __init__(self, name, force_pass=False, timeout_in_secs=0, max_retries=1): self._id = 0 self._name = name self._force_pass = force_pass self._timeout_in_secs = timeout_in_secs self._max_retries = max_retries self._result = STRATEGY_STEP_RESULT.INITIAL self._result_reason = '' self._stage_reference = None self._start_date_time = '' self._end_date_time = '' @property def name(self): """ Returns the name of the step """ return self._name @property def id(self): """ Returns the id of the step """ return self._id @id.setter def id(self, value): """ Sets the id of the step """ self._id = value @property def force_pass(self): """ Returns the true if force_pass has been set, otherwise false """ return self._force_pass @property def max_retries(self): """ Returns the maximum retry attempts for step to be completed """ return self._max_retries @property def timeout_in_secs(self): """ Returns the maximum amount of time to wait for completion """ return self._timeout_in_secs @property def result(self): """ Returns the result of the step """ return self._result @result.setter def result(self, result): """ Updates the result of the step """ self._result = result @property def result_reason(self): """ Returns the reason for the result of the step """ return self._result_reason @result_reason.setter def result_reason(self, reason): """ Updates the reason for the result of the step """ self._result_reason = reason @property def start_date_time(self): """ Returns the start date-time of the step """ return self._start_date_time @start_date_time.setter def start_date_time(self, date_time_str): """ Updates the start date-time of the step """ self._start_date_time = date_time_str @property def end_date_time(self): """ Returns the end date-time of the step """ return self._end_date_time @end_date_time.setter def end_date_time(self, date_time_str): """ Updates the end date-time of the step """ self._end_date_time = date_time_str @property def strategy(self): """ Returns the strategy this step is a member of """ if self.phase is not None: return self.phase.strategy return None @property def phase(self): """ Returns the phase this step is a member of """ if self.stage is not None: return self.stage.phase return None @property def stage(self): """ Returns the stage this step is a member of """ if self._stage_reference is not None: return self._stage_reference() return None @stage.setter def stage(self, stage_value): """ Set the stage that this step is a member of """ self._stage_reference = weakref.ref(stage_value) def extend_timeout(self, timeout_in_secs): """ Allow the step timeout to be extended """ DLOG.verbose("Extending strategy step timeout for %s to %s." % (self._name, timeout_in_secs)) self._timeout_in_secs = timeout_in_secs if self._stage_reference is not None: self.stage.step_extend_timeout() def abort(self): """ Strategy Step Abort (can be overridden by child class) """ DLOG.info("Default strategy step abort for %s." % self._name) return [] def apply(self): """ Strategy Step Apply (expected to be overridden by child class) """ DLOG.verbose("Default strategy step apply for %s." % self._name) return STRATEGY_STEP_RESULT.SUCCESS, '' def complete(self, result, result_reason): """ Strategy Step Completed (can be overridden by child class) """ DLOG.verbose("Default strategy step complete for %s, result=%s, " "reason=%s." % (self._name, result, result_reason)) return result, result_reason def timeout(self): """ Strategy Step Timeout (can be overridden by child class) """ DLOG.verbose("Default strategy step timeout for %s, timeout=%s secs." % (self._name, self._timeout_in_secs)) return STRATEGY_STEP_RESULT.TIMED_OUT, '' def handle_event(self, event, event_data=None): """ Strategy Step Handle Event (expected to be overridden by child class) """ DLOG.verbose("Default strategy step handle event for %s." % self._name) return False def from_dict(self, data): """ Returns a strategy step object initialized using the given dictionary """ StrategyStep.__init__(self, data['name'], data['force_pass'], data['timeout'], data['max_retries']) self._result = data['result'] self._result_reason = data['result_reason'] self._start_date_time = data['start_date_time'] self._end_date_time = data['end_date_time'] return self def as_dict(self): """ Represent the strategy step as a dictionary """ data = dict() data['id'] = self._id data['name'] = self._name data['force_pass'] = self._force_pass data['timeout'] = self._timeout_in_secs data['max_retries'] = self._max_retries data['result'] = self._result data['result_reason'] = self._result_reason data['start_date_time'] = self._start_date_time data['end_date_time'] = self._end_date_time return data
0.79999
0.198646
import warnings import pandas as pd import numpy as np def simFireplace( temperature, occ_act, n_ovens=1, T_oven_on=5, t_cool=5.0, fullloadSteps=450, seed=None, ): """ Creates the profile of the heating of wood ovens based on the outside temperature and the activity of the occupants. The profile is generated based on stochastics. Parameters ---------- temperature: pandas.Series(), required Outside temperature profile of the location. occ_act: pandas.Series(), required Series of values between 0 and 1 desribing the share of overall active occpants at every time step. n_ovens: int, optional (default:1) Number of ovens in the building. T_oven_on: int or float, optional (default:5.) Threeshold outside temperature [°C] when the oven is turned on. t_cool: int, optional (default:5) Number of timesteps till when the oven is cooled down again. fullloadSteps: int or float, optional (default:450) Resulting number of full load timesteps. Attention: This value is not exact since it is a stochastic profile generation. seed: int, optional (default:None) Seed required for reproduceability. If none, it is completely random. Returns ---------- load_profile: pandas.Series() Relative load profile of the ovens in kW/kWp. """ # Oven is only turned under a temperature threeshold tempBool = temperature < T_oven_on # Increase probability that the oven is turned on in case it is colder outside relCold = (T_oven_on - temperature) / (T_oven_on - temperature.min()) # Caclulate fire activation probability prob = occ_act.values * tempBool.values * relCold.values # avoid rounding errors prob[prob < 0] = 0 load_profile = pd.Series(0, index=temperature.index) for n in range(int(n_ovens)): # Modifier to reduce probability in order to fit the full load hours p_mod = fullloadSteps / (prob.sum() * t_cool / 2) overallProb = prob * p_mod overallProb[overallProb > 1.0] = 1.0 # Binary decision if an oven can be activated initLogArr = pd.Series(np.random.RandomState(seed).binomial(1, overallProb)) # create the profile heatLoad = [] loadBefore = 0 for initLog in initLogArr: if initLog: load = 1.0 else: if loadBefore > 0.001: load = loadBefore - 1.0 / t_cool else: load = 0 heatLoad.append(load) loadBefore = load load_profile += pd.Series(heatLoad, index=temperature.index) profile = load_profile / n_ovens if abs(profile.sum() - fullloadSteps) > 100: warnings.warn( "Fullload hour deviation is higher than 100. " + "Input parameters make it difficult or impossible " + "to generate the expected profile" ) return load_profile / n_ovens
tsib/renewables/fireplace.py
import warnings import pandas as pd import numpy as np def simFireplace( temperature, occ_act, n_ovens=1, T_oven_on=5, t_cool=5.0, fullloadSteps=450, seed=None, ): """ Creates the profile of the heating of wood ovens based on the outside temperature and the activity of the occupants. The profile is generated based on stochastics. Parameters ---------- temperature: pandas.Series(), required Outside temperature profile of the location. occ_act: pandas.Series(), required Series of values between 0 and 1 desribing the share of overall active occpants at every time step. n_ovens: int, optional (default:1) Number of ovens in the building. T_oven_on: int or float, optional (default:5.) Threeshold outside temperature [°C] when the oven is turned on. t_cool: int, optional (default:5) Number of timesteps till when the oven is cooled down again. fullloadSteps: int or float, optional (default:450) Resulting number of full load timesteps. Attention: This value is not exact since it is a stochastic profile generation. seed: int, optional (default:None) Seed required for reproduceability. If none, it is completely random. Returns ---------- load_profile: pandas.Series() Relative load profile of the ovens in kW/kWp. """ # Oven is only turned under a temperature threeshold tempBool = temperature < T_oven_on # Increase probability that the oven is turned on in case it is colder outside relCold = (T_oven_on - temperature) / (T_oven_on - temperature.min()) # Caclulate fire activation probability prob = occ_act.values * tempBool.values * relCold.values # avoid rounding errors prob[prob < 0] = 0 load_profile = pd.Series(0, index=temperature.index) for n in range(int(n_ovens)): # Modifier to reduce probability in order to fit the full load hours p_mod = fullloadSteps / (prob.sum() * t_cool / 2) overallProb = prob * p_mod overallProb[overallProb > 1.0] = 1.0 # Binary decision if an oven can be activated initLogArr = pd.Series(np.random.RandomState(seed).binomial(1, overallProb)) # create the profile heatLoad = [] loadBefore = 0 for initLog in initLogArr: if initLog: load = 1.0 else: if loadBefore > 0.001: load = loadBefore - 1.0 / t_cool else: load = 0 heatLoad.append(load) loadBefore = load load_profile += pd.Series(heatLoad, index=temperature.index) profile = load_profile / n_ovens if abs(profile.sum() - fullloadSteps) > 100: warnings.warn( "Fullload hour deviation is higher than 100. " + "Input parameters make it difficult or impossible " + "to generate the expected profile" ) return load_profile / n_ovens
0.789761
0.543348
import re import simple_history from django import forms from django.contrib import admin, messages from django.contrib.admin import TabularInline from django.db.models import Count, Exists, OuterRef from django.utils import timezone from django.utils.safestring import mark_safe from clubs.management.commands.merge_duplicates import merge_clubs, merge_tags from clubs.management.commands.remind import send_reminder_to_club from clubs.models import ( AdminNote, Advisor, ApplicationCommittee, ApplicationMultipleChoice, ApplicationQuestion, ApplicationQuestionResponse, ApplicationSubmission, Asset, Badge, Club, ClubApplication, ClubFair, ClubFairBooth, ClubFairRegistration, ClubVisit, Event, Favorite, Major, Membership, MembershipInvite, MembershipRequest, Note, NoteTag, Profile, QuestionAnswer, RecurringEvent, Report, School, SearchQuery, StudentType, Subscribe, Tag, TargetMajor, TargetSchool, TargetStudentType, TargetYear, Testimonial, Year, ZoomMeetingVisit, ) class HasOwnerListFilter(admin.SimpleListFilter): title = "has owner" parameter_name = "has_owner" def lookups(self, request, model_admin): return [("true", "True"), ("false", "False")] def queryset(self, request, queryset): val = self.value() if val: return queryset.filter(has_owner=val == "true") else: return queryset class HasInviteListFilter(admin.SimpleListFilter): title = "has invite" parameter_name = "has_invite" def lookups(self, request, model_admin): return [("true", "True"), ("false", "False")] def queryset(self, request, queryset): val = self.value() if val: return queryset.filter(has_invite=val == "true") else: return queryset def do_merge_clubs(modeladmin, request, queryset): if queryset.count() < 2: modeladmin.message_user( request, "You must select at least two clubs to merge!", level=messages.ERROR, ) return if queryset.count() > 5: modeladmin.message_user( request, "You have selected more than 5 clubs, " "you probably do not want to do this.", level=messages.ERROR, ) return club_names = list(queryset.order_by("name").values_list("name", flat=True)) tags = list(queryset) first, rest = tags[0], tags[1:] for club in rest: merge_clubs(first, club) modeladmin.message_user( request, "Merged the following clubs: {} into {}".format( ", ".join(club_names), first.name ), level=messages.SUCCESS, ) do_merge_clubs.short_description = "Merge selected clubs" def send_edit_reminder(modeladmin, request, queryset): success_count = 0 total_count = 0 for club in queryset.order_by("code"): if send_reminder_to_club(club): success_count += 1 total_count += 1 modeladmin.message_user( request, "Sent edit page reminder emails to {}/{} club(s).".format( success_count, total_count ), level=messages.SUCCESS, ) send_edit_reminder.short_description = "Send edit page reminder" def mark_approved(modeladmin, request, queryset): if not request.user.has_perm("clubs.approve_club"): modeladmin.message_user( request, "You do not have permission to approve clubs!", level=messages.ERROR, ) return num_updated = queryset.filter(approved=False).update( approved=True, approved_by=request.user, approved_on=timezone.now() ) modeladmin.message_user( request, "Marked {} club(s) as approved!".format(num_updated), level=messages.SUCCESS, ) mark_approved.short_description = "Approve clubs" class ClubAdminForm(forms.ModelForm): parent_orgs = forms.ModelMultipleChoiceField( queryset=Club.objects.annotate(num_children=Count("children_orgs")).order_by( "-num_children" ), required=False, ) class ClubChildrenInline(TabularInline): model = Club.children_orgs.through fk_name = "to_club" extra = 0 verbose_name = "Children org" verbose_name_plural = "Children orgs" class ClubAdmin(simple_history.admin.SimpleHistoryAdmin): search_fields = ("name", "subtitle", "email", "code") list_display = ("name", "email", "has_owner", "has_invite", "active", "approved") list_filter = ( "size", "application_required", "accepting_members", "enables_subscription", "recruiting_cycle", "active", "approved", HasOwnerListFilter, HasInviteListFilter, ) inlines = [ClubChildrenInline] actions = [do_merge_clubs, send_edit_reminder, mark_approved] form = ClubAdminForm def get_queryset(self, request): return ( super() .get_queryset(request) .annotate( has_owner=Exists( Membership.objects.filter(club=OuterRef("pk"), role__lte=0) ), has_invite=Exists(MembershipInvite.objects.filter(club=OuterRef("pk"))), ) ) def has_invite(self, obj): return obj.has_invite has_invite.boolean = True def has_owner(self, obj): return obj.has_owner has_owner.boolean = True class ClubFairAdmin(admin.ModelAdmin): list_display = ("name", "organization", "contact", "start_time") search_fields = ("name", "organization", "contact") list_filter = ("start_time", "end_time") class EventAdmin(admin.ModelAdmin): list_display = ("name", "club", "type", "start_time", "end_time") search_fields = ("name", "club__name") list_filter = ("start_time", "end_time") def club(self, obj): return obj.club.name class FavoriteAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name class SubscribeAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club", "email") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name def email(self, obj): return obj.person.email class MembershipRequestAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club", "email", "withdrew", "is_member") list_filter = ("withdrew",) def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name def email(self, obj): return obj.person.email def is_member(self, obj): return obj.club.membership_set.filter(person__pk=obj.person.pk).exists() is_member.boolean = True class MembershipAdmin(admin.ModelAdmin): search_fields = ( "person__username", "person__email", "club__name", "club__pk", "title", ) list_display = ("person", "club", "role", "title") list_filter = ("role", "active", "public") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name class ProfileAdmin(admin.ModelAdmin): search_fields = ("user__username", "user__email") list_display = ("user", "email", "graduation_year", "studies", "has_been_prompted") list_filter = ("graduation_year", "school", "major", "has_been_prompted") def email(self, obj): return str(obj.user.email or None) def studies(self, obj): major = ", ".join(obj.major.values_list("name", flat=True)) school = ", ".join(obj.school.values_list("name", flat=True)) return "{} - {}".format(school or None, major or None) class MembershipInviteAdmin(admin.ModelAdmin): search_fields = ("email", "club__name", "club__pk") list_display = ("email", "club", "role", "title", "active") list_filter = ("role", "active") def club(self, obj): return obj.club.name class AdvisorAdmin(admin.ModelAdmin): search_fields = ("name", "title", "email", "phone", "club__name") list_display = ("name", "title", "email", "phone", "club", "public") def club(self, obj): return obj.club.name def do_merge_tags(modeladmin, request, queryset): if queryset.count() < 2: modeladmin.message_user( request, "You must select at least two tags to merge!", level=messages.ERROR ) return tag_names = list(queryset.order_by("name").values_list("name", flat=True)) tags = list(queryset) first, rest = tags[0], tags[1:] for tag in rest: merge_tags(first, tag) modeladmin.message_user( request, "Merged the following tags: {} into {}".format( ", ".join(tag_names), first.name ), level=messages.SUCCESS, ) do_merge_tags.short_description = "Merge selected tags" class TagAdmin(admin.ModelAdmin): def club_count(self, obj): return obj.club_set.count() search_fields = ("name",) list_display = ("name", "club_count") actions = [do_merge_tags] class BadgeAdmin(admin.ModelAdmin): def club_count(self, obj): return obj.club_set.count() def badge_color(self, obj): if not re.match(r"^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", obj.color): return obj.color return mark_safe( f"<div style='background-color: #{obj.color}; \ width:1em; \ height:1em; \ border:1px solid black; \ border-radius:3px' />" ) search_fields = ("label",) list_display = ("label", "purpose", "org", "club_count", "badge_color", "visible") list_filter = ("visible", "purpose") actions = [do_merge_tags] class MajorAdmin(admin.ModelAdmin): search_fields = ("name",) class ReportAdmin(admin.ModelAdmin): search_fields = ("name", "description") list_display = ("name", "creator", "public") list_filter = ("created_at", "public") class YearAdmin(admin.ModelAdmin): search_fields = ("name",) list_display = ("name", "year") class QuestionAnswerAdmin(admin.ModelAdmin): search_fields = ("question", "answer") list_display = ("club", "question", "answer", "approved") list_filter = ("approved", "updated_at") class ZoomMeetingVisitAdmin(admin.ModelAdmin): search_fields = ("person__username", "event__club__code") list_display = ("person", "event", "join_time") list_filter = (("leave_time", admin.EmptyFieldListFilter),) admin.site.register(Asset) admin.site.register(ApplicationCommittee) admin.site.register(ApplicationMultipleChoice) admin.site.register(ApplicationQuestion) admin.site.register(ApplicationQuestionResponse) admin.site.register(ApplicationSubmission) admin.site.register(Advisor, AdvisorAdmin) admin.site.register(Club, ClubAdmin) admin.site.register(ClubFair, ClubFairAdmin) admin.site.register(ClubApplication) admin.site.register(ClubFairRegistration) admin.site.register(ClubVisit) admin.site.register(Badge, BadgeAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Favorite, FavoriteAdmin) admin.site.register(School) admin.site.register(SearchQuery) admin.site.register(Subscribe, SubscribeAdmin) admin.site.register(MembershipRequest, MembershipRequestAdmin) admin.site.register(Major, MajorAdmin) admin.site.register(Membership, MembershipAdmin) admin.site.register(MembershipInvite, MembershipInviteAdmin) admin.site.register(Profile, ProfileAdmin) admin.site.register(QuestionAnswer, QuestionAnswerAdmin) admin.site.register(RecurringEvent) admin.site.register(Report, ReportAdmin) admin.site.register(Tag, TagAdmin) admin.site.register(TargetMajor) admin.site.register(TargetSchool) admin.site.register(TargetYear) admin.site.register(TargetStudentType) admin.site.register(Testimonial) admin.site.register(StudentType) admin.site.register(Note) admin.site.register(ClubFairBooth) admin.site.register(NoteTag) admin.site.register(Year, YearAdmin) admin.site.register(ZoomMeetingVisit, ZoomMeetingVisitAdmin) admin.site.register(AdminNote)
backend/clubs/admin.py
import re import simple_history from django import forms from django.contrib import admin, messages from django.contrib.admin import TabularInline from django.db.models import Count, Exists, OuterRef from django.utils import timezone from django.utils.safestring import mark_safe from clubs.management.commands.merge_duplicates import merge_clubs, merge_tags from clubs.management.commands.remind import send_reminder_to_club from clubs.models import ( AdminNote, Advisor, ApplicationCommittee, ApplicationMultipleChoice, ApplicationQuestion, ApplicationQuestionResponse, ApplicationSubmission, Asset, Badge, Club, ClubApplication, ClubFair, ClubFairBooth, ClubFairRegistration, ClubVisit, Event, Favorite, Major, Membership, MembershipInvite, MembershipRequest, Note, NoteTag, Profile, QuestionAnswer, RecurringEvent, Report, School, SearchQuery, StudentType, Subscribe, Tag, TargetMajor, TargetSchool, TargetStudentType, TargetYear, Testimonial, Year, ZoomMeetingVisit, ) class HasOwnerListFilter(admin.SimpleListFilter): title = "has owner" parameter_name = "has_owner" def lookups(self, request, model_admin): return [("true", "True"), ("false", "False")] def queryset(self, request, queryset): val = self.value() if val: return queryset.filter(has_owner=val == "true") else: return queryset class HasInviteListFilter(admin.SimpleListFilter): title = "has invite" parameter_name = "has_invite" def lookups(self, request, model_admin): return [("true", "True"), ("false", "False")] def queryset(self, request, queryset): val = self.value() if val: return queryset.filter(has_invite=val == "true") else: return queryset def do_merge_clubs(modeladmin, request, queryset): if queryset.count() < 2: modeladmin.message_user( request, "You must select at least two clubs to merge!", level=messages.ERROR, ) return if queryset.count() > 5: modeladmin.message_user( request, "You have selected more than 5 clubs, " "you probably do not want to do this.", level=messages.ERROR, ) return club_names = list(queryset.order_by("name").values_list("name", flat=True)) tags = list(queryset) first, rest = tags[0], tags[1:] for club in rest: merge_clubs(first, club) modeladmin.message_user( request, "Merged the following clubs: {} into {}".format( ", ".join(club_names), first.name ), level=messages.SUCCESS, ) do_merge_clubs.short_description = "Merge selected clubs" def send_edit_reminder(modeladmin, request, queryset): success_count = 0 total_count = 0 for club in queryset.order_by("code"): if send_reminder_to_club(club): success_count += 1 total_count += 1 modeladmin.message_user( request, "Sent edit page reminder emails to {}/{} club(s).".format( success_count, total_count ), level=messages.SUCCESS, ) send_edit_reminder.short_description = "Send edit page reminder" def mark_approved(modeladmin, request, queryset): if not request.user.has_perm("clubs.approve_club"): modeladmin.message_user( request, "You do not have permission to approve clubs!", level=messages.ERROR, ) return num_updated = queryset.filter(approved=False).update( approved=True, approved_by=request.user, approved_on=timezone.now() ) modeladmin.message_user( request, "Marked {} club(s) as approved!".format(num_updated), level=messages.SUCCESS, ) mark_approved.short_description = "Approve clubs" class ClubAdminForm(forms.ModelForm): parent_orgs = forms.ModelMultipleChoiceField( queryset=Club.objects.annotate(num_children=Count("children_orgs")).order_by( "-num_children" ), required=False, ) class ClubChildrenInline(TabularInline): model = Club.children_orgs.through fk_name = "to_club" extra = 0 verbose_name = "Children org" verbose_name_plural = "Children orgs" class ClubAdmin(simple_history.admin.SimpleHistoryAdmin): search_fields = ("name", "subtitle", "email", "code") list_display = ("name", "email", "has_owner", "has_invite", "active", "approved") list_filter = ( "size", "application_required", "accepting_members", "enables_subscription", "recruiting_cycle", "active", "approved", HasOwnerListFilter, HasInviteListFilter, ) inlines = [ClubChildrenInline] actions = [do_merge_clubs, send_edit_reminder, mark_approved] form = ClubAdminForm def get_queryset(self, request): return ( super() .get_queryset(request) .annotate( has_owner=Exists( Membership.objects.filter(club=OuterRef("pk"), role__lte=0) ), has_invite=Exists(MembershipInvite.objects.filter(club=OuterRef("pk"))), ) ) def has_invite(self, obj): return obj.has_invite has_invite.boolean = True def has_owner(self, obj): return obj.has_owner has_owner.boolean = True class ClubFairAdmin(admin.ModelAdmin): list_display = ("name", "organization", "contact", "start_time") search_fields = ("name", "organization", "contact") list_filter = ("start_time", "end_time") class EventAdmin(admin.ModelAdmin): list_display = ("name", "club", "type", "start_time", "end_time") search_fields = ("name", "club__name") list_filter = ("start_time", "end_time") def club(self, obj): return obj.club.name class FavoriteAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name class SubscribeAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club", "email") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name def email(self, obj): return obj.person.email class MembershipRequestAdmin(admin.ModelAdmin): search_fields = ("person__username", "person__email", "club__name", "club__pk") list_display = ("person", "club", "email", "withdrew", "is_member") list_filter = ("withdrew",) def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name def email(self, obj): return obj.person.email def is_member(self, obj): return obj.club.membership_set.filter(person__pk=obj.person.pk).exists() is_member.boolean = True class MembershipAdmin(admin.ModelAdmin): search_fields = ( "person__username", "person__email", "club__name", "club__pk", "title", ) list_display = ("person", "club", "role", "title") list_filter = ("role", "active", "public") def person(self, obj): return obj.person.username def club(self, obj): return obj.club.name class ProfileAdmin(admin.ModelAdmin): search_fields = ("user__username", "user__email") list_display = ("user", "email", "graduation_year", "studies", "has_been_prompted") list_filter = ("graduation_year", "school", "major", "has_been_prompted") def email(self, obj): return str(obj.user.email or None) def studies(self, obj): major = ", ".join(obj.major.values_list("name", flat=True)) school = ", ".join(obj.school.values_list("name", flat=True)) return "{} - {}".format(school or None, major or None) class MembershipInviteAdmin(admin.ModelAdmin): search_fields = ("email", "club__name", "club__pk") list_display = ("email", "club", "role", "title", "active") list_filter = ("role", "active") def club(self, obj): return obj.club.name class AdvisorAdmin(admin.ModelAdmin): search_fields = ("name", "title", "email", "phone", "club__name") list_display = ("name", "title", "email", "phone", "club", "public") def club(self, obj): return obj.club.name def do_merge_tags(modeladmin, request, queryset): if queryset.count() < 2: modeladmin.message_user( request, "You must select at least two tags to merge!", level=messages.ERROR ) return tag_names = list(queryset.order_by("name").values_list("name", flat=True)) tags = list(queryset) first, rest = tags[0], tags[1:] for tag in rest: merge_tags(first, tag) modeladmin.message_user( request, "Merged the following tags: {} into {}".format( ", ".join(tag_names), first.name ), level=messages.SUCCESS, ) do_merge_tags.short_description = "Merge selected tags" class TagAdmin(admin.ModelAdmin): def club_count(self, obj): return obj.club_set.count() search_fields = ("name",) list_display = ("name", "club_count") actions = [do_merge_tags] class BadgeAdmin(admin.ModelAdmin): def club_count(self, obj): return obj.club_set.count() def badge_color(self, obj): if not re.match(r"^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", obj.color): return obj.color return mark_safe( f"<div style='background-color: #{obj.color}; \ width:1em; \ height:1em; \ border:1px solid black; \ border-radius:3px' />" ) search_fields = ("label",) list_display = ("label", "purpose", "org", "club_count", "badge_color", "visible") list_filter = ("visible", "purpose") actions = [do_merge_tags] class MajorAdmin(admin.ModelAdmin): search_fields = ("name",) class ReportAdmin(admin.ModelAdmin): search_fields = ("name", "description") list_display = ("name", "creator", "public") list_filter = ("created_at", "public") class YearAdmin(admin.ModelAdmin): search_fields = ("name",) list_display = ("name", "year") class QuestionAnswerAdmin(admin.ModelAdmin): search_fields = ("question", "answer") list_display = ("club", "question", "answer", "approved") list_filter = ("approved", "updated_at") class ZoomMeetingVisitAdmin(admin.ModelAdmin): search_fields = ("person__username", "event__club__code") list_display = ("person", "event", "join_time") list_filter = (("leave_time", admin.EmptyFieldListFilter),) admin.site.register(Asset) admin.site.register(ApplicationCommittee) admin.site.register(ApplicationMultipleChoice) admin.site.register(ApplicationQuestion) admin.site.register(ApplicationQuestionResponse) admin.site.register(ApplicationSubmission) admin.site.register(Advisor, AdvisorAdmin) admin.site.register(Club, ClubAdmin) admin.site.register(ClubFair, ClubFairAdmin) admin.site.register(ClubApplication) admin.site.register(ClubFairRegistration) admin.site.register(ClubVisit) admin.site.register(Badge, BadgeAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Favorite, FavoriteAdmin) admin.site.register(School) admin.site.register(SearchQuery) admin.site.register(Subscribe, SubscribeAdmin) admin.site.register(MembershipRequest, MembershipRequestAdmin) admin.site.register(Major, MajorAdmin) admin.site.register(Membership, MembershipAdmin) admin.site.register(MembershipInvite, MembershipInviteAdmin) admin.site.register(Profile, ProfileAdmin) admin.site.register(QuestionAnswer, QuestionAnswerAdmin) admin.site.register(RecurringEvent) admin.site.register(Report, ReportAdmin) admin.site.register(Tag, TagAdmin) admin.site.register(TargetMajor) admin.site.register(TargetSchool) admin.site.register(TargetYear) admin.site.register(TargetStudentType) admin.site.register(Testimonial) admin.site.register(StudentType) admin.site.register(Note) admin.site.register(ClubFairBooth) admin.site.register(NoteTag) admin.site.register(Year, YearAdmin) admin.site.register(ZoomMeetingVisit, ZoomMeetingVisitAdmin) admin.site.register(AdminNote)
0.380183
0.132824
from pytest import raises # type: ignore from pygritia import * # pylint: disable=wildcard-import,unused-wildcard-import def test_if(): """Test for If""" cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = If(cond, sym[0]) assert str(expr) == 'If(cond, sym[0])' assert evaluate(expr, {cond: True, sym: arr}) == arr[0] assert evaluate(expr, {cond: False, sym: arr}) is None update(expr, 9, {cond: True, sym: arr}) assert arr[0] == 9 with raises(TypeError): update(expr, 12, {cond: False, sym: arr}) def test_if_then_else(): """Test for IfThenElse""" cond = symbol('cond') cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = IfThenElse(cond, sym[0], sym[1]) assert str(expr) == 'IfThenElse(cond, sym[0], sym[1])' assert evaluate(expr, {cond: True, sym: arr}) == arr[0] assert evaluate(expr, {cond: False, sym: arr}) == arr[1] update(expr, 9, {cond: True, sym: arr}) assert arr[0] == 9 and arr[1] == 2 update(expr, 12, {cond: False, sym: arr}) assert arr[0] == 9 and arr[1] == 12 def test_case(): """Test for Case""" cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = Case(cond, {'first': sym[0], 'second': sym[1]}, sym[2]) assert str(expr) == "Case(cond, {'first': sym[0], 'second': sym[1]}, sym[2])" assert evaluate(expr, {cond: 'first', sym: arr}) == arr[0] assert evaluate(expr, {cond: 'second', sym: arr}) == arr[1] assert evaluate(expr, {cond: 'third', sym: arr}) == arr[2] update(expr, 9, {cond: 'first', sym: arr}) assert arr == [9, 2, 3] update(expr, 12, {cond: 'second', sym: arr}) assert arr == [9, 12, 3] update(expr, 15, {cond: 'third', sym: arr}) assert arr == [9, 12, 15] expr = Case(cond, {'first': sym[0]}, None) assert str(expr) == "If(cond == 'first', sym[0])" def test_ensure(): """Test for Ensure""" obj = symbol('obj') expr = Ensure(obj, 'none') assert str(expr) == 'Ensure(obj)' assert evaluate(expr, {obj: None}) == 'none' assert evaluate(expr, {obj: 'hello'}) == 'hello'
tests/test_cases.py
from pytest import raises # type: ignore from pygritia import * # pylint: disable=wildcard-import,unused-wildcard-import def test_if(): """Test for If""" cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = If(cond, sym[0]) assert str(expr) == 'If(cond, sym[0])' assert evaluate(expr, {cond: True, sym: arr}) == arr[0] assert evaluate(expr, {cond: False, sym: arr}) is None update(expr, 9, {cond: True, sym: arr}) assert arr[0] == 9 with raises(TypeError): update(expr, 12, {cond: False, sym: arr}) def test_if_then_else(): """Test for IfThenElse""" cond = symbol('cond') cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = IfThenElse(cond, sym[0], sym[1]) assert str(expr) == 'IfThenElse(cond, sym[0], sym[1])' assert evaluate(expr, {cond: True, sym: arr}) == arr[0] assert evaluate(expr, {cond: False, sym: arr}) == arr[1] update(expr, 9, {cond: True, sym: arr}) assert arr[0] == 9 and arr[1] == 2 update(expr, 12, {cond: False, sym: arr}) assert arr[0] == 9 and arr[1] == 12 def test_case(): """Test for Case""" cond = symbol('cond') sym = symbol('sym') arr = [1, 2, 3] expr = Case(cond, {'first': sym[0], 'second': sym[1]}, sym[2]) assert str(expr) == "Case(cond, {'first': sym[0], 'second': sym[1]}, sym[2])" assert evaluate(expr, {cond: 'first', sym: arr}) == arr[0] assert evaluate(expr, {cond: 'second', sym: arr}) == arr[1] assert evaluate(expr, {cond: 'third', sym: arr}) == arr[2] update(expr, 9, {cond: 'first', sym: arr}) assert arr == [9, 2, 3] update(expr, 12, {cond: 'second', sym: arr}) assert arr == [9, 12, 3] update(expr, 15, {cond: 'third', sym: arr}) assert arr == [9, 12, 15] expr = Case(cond, {'first': sym[0]}, None) assert str(expr) == "If(cond == 'first', sym[0])" def test_ensure(): """Test for Ensure""" obj = symbol('obj') expr = Ensure(obj, 'none') assert str(expr) == 'Ensure(obj)' assert evaluate(expr, {obj: None}) == 'none' assert evaluate(expr, {obj: 'hello'}) == 'hello'
0.498291
0.757638
import ast import os.path from typing import List from typing import Tuple from all_repos_depends.errors import DependsError from all_repos_depends.lang import python from all_repos_depends.types import Depends class FindsInstallRequires(ast.NodeVisitor): def __init__(self) -> None: self.requires: List[Depends] = [] def visit_Call(self, node: ast.Call) -> None: if python.node_is_setup_call(node): for kwd in node.keywords: if ( kwd.arg == 'install_requires' and isinstance(kwd.value, ast.List) ): if all(isinstance(e, ast.Str) for e in kwd.value.elts): for elt in kwd.value.elts: assert isinstance(elt, ast.Str) req = python.to_depends('DEPENDS', elt.s) self.requires.append(req) else: raise DependsError( 'Had setup.py with install_requires but it was ' 'not a list of strings', ) self.generic_visit(node) def setup_py() -> Tuple[Depends, ...]: if not os.path.exists('setup.py'): return () visitor = FindsInstallRequires() visitor.visit(python.load_setup_py_ast()) return tuple(visitor.requires) def requirements_tools() -> Tuple[Depends, ...]: reqs_minimal = 'requirements-minimal.txt' reqs = 'requirements.txt' reqs_dev_minimal = 'requirements-dev-minimal.txt' reqs_dev = 'requirements-dev.txt' ret: List[Depends] = [] if os.path.exists(reqs_minimal) and os.path.exists(reqs): ret.extend(python.from_reqs_file('DEPENDS', reqs_minimal)) ret.extend(python.from_reqs_file('REQUIRES', reqs)) elif os.path.exists(reqs): ret.extend(python.from_reqs_file('REQUIRES', reqs)) if os.path.exists(reqs_dev_minimal) and os.path.exists(reqs_dev): ret.extend(python.from_reqs_file('DEPENDS_DEV', reqs_dev_minimal)) ret.extend(python.from_reqs_file('REQUIRES_DEV', reqs_dev)) elif os.path.exists(reqs_dev): ret.extend(python.from_reqs_file('DEPENDS_DEV', reqs_dev)) return tuple(ret)
all_repos_depends/depends.py
import ast import os.path from typing import List from typing import Tuple from all_repos_depends.errors import DependsError from all_repos_depends.lang import python from all_repos_depends.types import Depends class FindsInstallRequires(ast.NodeVisitor): def __init__(self) -> None: self.requires: List[Depends] = [] def visit_Call(self, node: ast.Call) -> None: if python.node_is_setup_call(node): for kwd in node.keywords: if ( kwd.arg == 'install_requires' and isinstance(kwd.value, ast.List) ): if all(isinstance(e, ast.Str) for e in kwd.value.elts): for elt in kwd.value.elts: assert isinstance(elt, ast.Str) req = python.to_depends('DEPENDS', elt.s) self.requires.append(req) else: raise DependsError( 'Had setup.py with install_requires but it was ' 'not a list of strings', ) self.generic_visit(node) def setup_py() -> Tuple[Depends, ...]: if not os.path.exists('setup.py'): return () visitor = FindsInstallRequires() visitor.visit(python.load_setup_py_ast()) return tuple(visitor.requires) def requirements_tools() -> Tuple[Depends, ...]: reqs_minimal = 'requirements-minimal.txt' reqs = 'requirements.txt' reqs_dev_minimal = 'requirements-dev-minimal.txt' reqs_dev = 'requirements-dev.txt' ret: List[Depends] = [] if os.path.exists(reqs_minimal) and os.path.exists(reqs): ret.extend(python.from_reqs_file('DEPENDS', reqs_minimal)) ret.extend(python.from_reqs_file('REQUIRES', reqs)) elif os.path.exists(reqs): ret.extend(python.from_reqs_file('REQUIRES', reqs)) if os.path.exists(reqs_dev_minimal) and os.path.exists(reqs_dev): ret.extend(python.from_reqs_file('DEPENDS_DEV', reqs_dev_minimal)) ret.extend(python.from_reqs_file('REQUIRES_DEV', reqs_dev)) elif os.path.exists(reqs_dev): ret.extend(python.from_reqs_file('DEPENDS_DEV', reqs_dev)) return tuple(ret)
0.496582
0.150903
import os import sys import yaml import desiutil import fitsio import desisim import argparse import os.path as path import numpy as np import astropy.io.fits as fits import matplotlib.pyplot as plt from desiutil import depend from astropy.convolution import convolve, Box1DKernel from pathlib import Path from desiutil.dust import mwdust_transmission from desiutil.log import get_logger from pkg_resources import resource_filename from scipy.interpolate import interp1d from astropy.table import Table, join from desispec.tsnr import template_ensemble, gfa_template_ensemble np.random.seed(seed=314) # AR/DK DESI spectra wavelengths # TODO: where are brz extraction wavelengths defined? https://github.com/desihub/desispec/issues/1006. wmin, wmax, wdelta = 3600, 9824, 0.8 wave = np.round(np.arange(wmin, wmax + wdelta, wdelta), 1) cslice = {"b": slice(0, 2751), "r": slice(2700, 5026), "z": slice(4900, 7781)} def parse(options=None): parser = argparse.ArgumentParser(description="Generate a sim. template ensemble stack of given type and write it to disk at --outdir.") parser.add_argument('--nmodel', type = int, default = 1000, required=False, help='Number of galaxies in the ensemble.') parser.add_argument('--tracer', type = str, default = 'bgs', required=True, help='Tracer to generate of [bgs, lrg, elg, qso].') parser.add_argument('--smooth', type=float, default=100., required=False, help='Smoothing scale [A] for DFLUX calc.') parser.add_argument('--config-filename', type = str, default = None, required=False, help='path to config filename (default is from python package desispec/data/tsnr/tsnr-config-{tracer}.yaml)') parser.add_argument('--nz-filename', type = str, default = None, required=False, help='path to n(z) filename (default is from $DESIMODEL/data/targets/nz_{tracer}.dat)') parser.add_argument('--outdir', type = str, default = 'bgs', required=True, help='Directory to write to.') parser.add_argument('--no-nz-convolution', action='store_true', help='Dont convolve each template dF^2 with redshift distribution') parser.add_argument('--mag-range', action='store_true', help='Monte Carlo the full mag range (given in config file) instead of using the same effective mag for all templates') args = None if options is None: args = parser.parse_args() else: args = parser.parse_args(options) return args def main(args): if args.tracer == 'gpb': templates = gfa_template_ensemble() templates.compute() templates.plot() templates.write(dirname=args.outdir) elif args.tracer in ['bgs', 'lrg', 'elg', 'lya', 'qso']: templates = template_ensemble(tracer=args.tracer,config_filename=args.config_filename) templates.compute(nmodel=args.nmodel, smooth=args.smooth, nz_table_filename=args.nz_filename, convolve_to_nz=(not args.no_nz_convolution), single_mag=(not args.mag_range)) filename = "{}/tsnr-ensemble-{}.fits".format(args.outdir,args.tracer) templates.write(filename) else: raise ValueError('Unknown tracer {} to compute.'.format(args.tracer)) if __name__ == '__main__': print("please run desi_compute_tsnr_ensemble")
py/desispec/scripts/compute_tsnr_ensemble.py
import os import sys import yaml import desiutil import fitsio import desisim import argparse import os.path as path import numpy as np import astropy.io.fits as fits import matplotlib.pyplot as plt from desiutil import depend from astropy.convolution import convolve, Box1DKernel from pathlib import Path from desiutil.dust import mwdust_transmission from desiutil.log import get_logger from pkg_resources import resource_filename from scipy.interpolate import interp1d from astropy.table import Table, join from desispec.tsnr import template_ensemble, gfa_template_ensemble np.random.seed(seed=314) # AR/DK DESI spectra wavelengths # TODO: where are brz extraction wavelengths defined? https://github.com/desihub/desispec/issues/1006. wmin, wmax, wdelta = 3600, 9824, 0.8 wave = np.round(np.arange(wmin, wmax + wdelta, wdelta), 1) cslice = {"b": slice(0, 2751), "r": slice(2700, 5026), "z": slice(4900, 7781)} def parse(options=None): parser = argparse.ArgumentParser(description="Generate a sim. template ensemble stack of given type and write it to disk at --outdir.") parser.add_argument('--nmodel', type = int, default = 1000, required=False, help='Number of galaxies in the ensemble.') parser.add_argument('--tracer', type = str, default = 'bgs', required=True, help='Tracer to generate of [bgs, lrg, elg, qso].') parser.add_argument('--smooth', type=float, default=100., required=False, help='Smoothing scale [A] for DFLUX calc.') parser.add_argument('--config-filename', type = str, default = None, required=False, help='path to config filename (default is from python package desispec/data/tsnr/tsnr-config-{tracer}.yaml)') parser.add_argument('--nz-filename', type = str, default = None, required=False, help='path to n(z) filename (default is from $DESIMODEL/data/targets/nz_{tracer}.dat)') parser.add_argument('--outdir', type = str, default = 'bgs', required=True, help='Directory to write to.') parser.add_argument('--no-nz-convolution', action='store_true', help='Dont convolve each template dF^2 with redshift distribution') parser.add_argument('--mag-range', action='store_true', help='Monte Carlo the full mag range (given in config file) instead of using the same effective mag for all templates') args = None if options is None: args = parser.parse_args() else: args = parser.parse_args(options) return args def main(args): if args.tracer == 'gpb': templates = gfa_template_ensemble() templates.compute() templates.plot() templates.write(dirname=args.outdir) elif args.tracer in ['bgs', 'lrg', 'elg', 'lya', 'qso']: templates = template_ensemble(tracer=args.tracer,config_filename=args.config_filename) templates.compute(nmodel=args.nmodel, smooth=args.smooth, nz_table_filename=args.nz_filename, convolve_to_nz=(not args.no_nz_convolution), single_mag=(not args.mag_range)) filename = "{}/tsnr-ensemble-{}.fits".format(args.outdir,args.tracer) templates.write(filename) else: raise ValueError('Unknown tracer {} to compute.'.format(args.tracer)) if __name__ == '__main__': print("please run desi_compute_tsnr_ensemble")
0.229449
0.168275
from Estoque import Estoque_Menu list_estoque = list() # Contém todas as produtos registrados e seu disponibilidade list_verifica_id = list() # Contém todos os ids já registrados para tratamento de erro list_entrada_de_produto = list() # Registra toda a entrada de produto list_saída_de_produto = list() # Registra toda a saída de produto dict_produto = dict() # Armazena todas as informações do produto dict_nRegistro = dict() # Reúne as informações do produto e seu ID de reconhecimento def registrar_produto_novo(): # Registra produtos ainda não existentes no estoque class Produto(): def __init__(self): self.__produto_id:int = int(input('ID do Produto : ')) self.__nome:str = input('Nome do produto : ') self.__quantidade:int = int(input('Quantidade : ')) self.tamanho = input('Tamanho do produto : ') self.cor:str = input('Cor do Produto : ') self.__data = input('Data de entrada do produto : ') self.__nRegistro:int = len(list_estoque) + 1 dict_produto['nRegistro']:int = self.__nRegistro dict_produto['Nome']:str = self.__nome.title() dict_produto['Quantidade']:int = self.__quantidade dict_produto['Tamanho'] = self.tamanho dict_produto['Cor']:str = self.cor dict_produto['Data'] = self.__data dict_nRegistro['ID DO PRODUTO']:int = self.__produto_id dict_nRegistro['INFO']:str = dict_produto.copy() def __repr__(self): Produto() Produto() if dict_nRegistro['ID DO PRODUTO'] not in list_verifica_id: list_entrada_de_produto.append(dict_produto.copy()) list_estoque.append(dict_nRegistro.copy()) print('\n', dict_produto, '- REGISTRADO') # Adiciona o produto ao estoque e controle de entrada else: print('TÁ ERRADO ISSO AI IRMÃO') list_verifica_id.append(dict_nRegistro.copy()['ID DO PRODUTO']) # list_verifica_registro.append(dict_produto.copy()['nRegistro']) def controle(): # Registra toda a entrada e saída de produtos para controlar o estoque def menu_registrar_entrada_saida(): def registra_entrada_de_produto(): # Registra toda a entrada de produtos while True: try: id_quest: int = int(input('\nDigite o ID do produto ao qual deseja registrar entrada : ')) if id_quest not in list_verifica_id: print(f'O ID digitado ({id_quest}) não existe no estoque') else: break except: print('\n!Erro') print('Use apenas valores valídos') continue nome_produto: dict = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Nome'] # Acessa o nome do produto print('\nProduto', f'"{nome_produto}"', ' - SELECIONADO') quantidade:str = int(input(f'\nQuantidade a ser adicionada ao estoque do "{nome_produto}" : ')) list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] += quantidade # Soma a quantia solicitada ao estoque x: dict = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] print(f'\nQuantidade do produto {nome_produto} atualiza : "{x}"') def registrar_saída_de_produto(): # Registra toda a saída de produtos while True: try: id_quest: int = int(input('\nDigite o ID do produto ao qual deseja registrar saída : ')) if id_quest not in list_verifica_id: print(f'O ID digitado ({id_quest}) não existe no estoque') else:break except: print('\n!Erro') print('Use apenas valores valídos') continue nome_produto:str = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Nome'] # Acessa o nome do produto print('\nProduto', f'"{nome_produto}"', ' - SELECIONADO') quantidade:int = int(input(f'\nQuantidade a ser removida do estoque do "{nome_produto}" : ')) quantidade_nova = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] - quantidade # Subtrai a quantia solicitada do estoque print(f'\n Quantidade do produto "{nome_produto}" atualiza : "Quantidade : {quantidade_nova}"') def menu_entrada_saida(): def entrada_de_entrada(): for produto in list_entrada_de_produto: print(produto) def saida_de_saida(): for produto in list_saída_de_produto: print(produto) print('*' * 40) print(' CONTROLE DE ESTOQUE') print('*' * 40) print('\n[1] REGISTRAR ENTRADA/SAÍDA DE PRODUTO' '\n[2] VER ENTRADA/SAÍDA DE PRODUTOS' '\n[3] VOLTAR') while True: try: menu_quest: int = int(input('\nESCOLHA UMA DAS OPÇÕES ACIMA : \n')) if menu_quest == 1: menu_registrar_entrada_saida() break elif menu_quest == 2: menu_entrada_saida() break elif menu_quest == 3: Estoque_Menu.menu_estoque() break else: print('\n!Erro') print('!Digite uma opção valída') except: print('\n!Erro') print('!Digite uma opção valída') def atualização_cadastral() -> dict : # Atualiza o armazenamento de informações de um produto mal registrado while True: quest: int = int(input('\nDigite o número de id do produto : ')) if quest in list_verifica_id: break elif quest != int: print('\n!Erro') print('Use apenas valores valídos') continue else: print('\n!Erro'), print('!Não encotrado') index:int = list_verifica_id.index(quest) # Acessa o index do produto selecionado class AtualizaProduto(): # Coleta e altera as informações do produto selecionado def __init__(self): self.__nome:str = input('Nome do produto : ') self.__quantidade:int = int(input('Quantidade : ')) self.tamanho = input('Tamanho do produto : ') self.cor:str = input('Cor do Produto : ') self.__data = input('Data de entrada do produto : ') self.__nRegistro:int = list_estoque[index]['INFO']['nRegistro'] list_estoque[index]['INFO']['nRegistro']:int = self.__nRegistro list_estoque[index]['INFO']['Nome']:str = self.__nome.title() list_estoque[index]['INFO']['Quantidade']:int = self.__quantidade list_estoque[index]['INFO']['Tamanho'] = self.tamanho list_estoque[index]['INFO']['Cor']:str = self.cor list_estoque[index]['INFO']['Data'] = self.__data def __repr__(self): AtualizaProduto() AtualizaProduto() print('\n', list_estoque[index]['INFO'], '- ATUALIZADO') def estoque() -> list: # Imprime todo o estoque disponível for c in list_estoque: print(c)
!Loja (Canceled Version)!/Estoque/Backup.py
from Estoque import Estoque_Menu list_estoque = list() # Contém todas as produtos registrados e seu disponibilidade list_verifica_id = list() # Contém todos os ids já registrados para tratamento de erro list_entrada_de_produto = list() # Registra toda a entrada de produto list_saída_de_produto = list() # Registra toda a saída de produto dict_produto = dict() # Armazena todas as informações do produto dict_nRegistro = dict() # Reúne as informações do produto e seu ID de reconhecimento def registrar_produto_novo(): # Registra produtos ainda não existentes no estoque class Produto(): def __init__(self): self.__produto_id:int = int(input('ID do Produto : ')) self.__nome:str = input('Nome do produto : ') self.__quantidade:int = int(input('Quantidade : ')) self.tamanho = input('Tamanho do produto : ') self.cor:str = input('Cor do Produto : ') self.__data = input('Data de entrada do produto : ') self.__nRegistro:int = len(list_estoque) + 1 dict_produto['nRegistro']:int = self.__nRegistro dict_produto['Nome']:str = self.__nome.title() dict_produto['Quantidade']:int = self.__quantidade dict_produto['Tamanho'] = self.tamanho dict_produto['Cor']:str = self.cor dict_produto['Data'] = self.__data dict_nRegistro['ID DO PRODUTO']:int = self.__produto_id dict_nRegistro['INFO']:str = dict_produto.copy() def __repr__(self): Produto() Produto() if dict_nRegistro['ID DO PRODUTO'] not in list_verifica_id: list_entrada_de_produto.append(dict_produto.copy()) list_estoque.append(dict_nRegistro.copy()) print('\n', dict_produto, '- REGISTRADO') # Adiciona o produto ao estoque e controle de entrada else: print('TÁ ERRADO ISSO AI IRMÃO') list_verifica_id.append(dict_nRegistro.copy()['ID DO PRODUTO']) # list_verifica_registro.append(dict_produto.copy()['nRegistro']) def controle(): # Registra toda a entrada e saída de produtos para controlar o estoque def menu_registrar_entrada_saida(): def registra_entrada_de_produto(): # Registra toda a entrada de produtos while True: try: id_quest: int = int(input('\nDigite o ID do produto ao qual deseja registrar entrada : ')) if id_quest not in list_verifica_id: print(f'O ID digitado ({id_quest}) não existe no estoque') else: break except: print('\n!Erro') print('Use apenas valores valídos') continue nome_produto: dict = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Nome'] # Acessa o nome do produto print('\nProduto', f'"{nome_produto}"', ' - SELECIONADO') quantidade:str = int(input(f'\nQuantidade a ser adicionada ao estoque do "{nome_produto}" : ')) list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] += quantidade # Soma a quantia solicitada ao estoque x: dict = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] print(f'\nQuantidade do produto {nome_produto} atualiza : "{x}"') def registrar_saída_de_produto(): # Registra toda a saída de produtos while True: try: id_quest: int = int(input('\nDigite o ID do produto ao qual deseja registrar saída : ')) if id_quest not in list_verifica_id: print(f'O ID digitado ({id_quest}) não existe no estoque') else:break except: print('\n!Erro') print('Use apenas valores valídos') continue nome_produto:str = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Nome'] # Acessa o nome do produto print('\nProduto', f'"{nome_produto}"', ' - SELECIONADO') quantidade:int = int(input(f'\nQuantidade a ser removida do estoque do "{nome_produto}" : ')) quantidade_nova = list_estoque[list_verifica_id.index(id_quest)]['INFO']['Quantidade'] - quantidade # Subtrai a quantia solicitada do estoque print(f'\n Quantidade do produto "{nome_produto}" atualiza : "Quantidade : {quantidade_nova}"') def menu_entrada_saida(): def entrada_de_entrada(): for produto in list_entrada_de_produto: print(produto) def saida_de_saida(): for produto in list_saída_de_produto: print(produto) print('*' * 40) print(' CONTROLE DE ESTOQUE') print('*' * 40) print('\n[1] REGISTRAR ENTRADA/SAÍDA DE PRODUTO' '\n[2] VER ENTRADA/SAÍDA DE PRODUTOS' '\n[3] VOLTAR') while True: try: menu_quest: int = int(input('\nESCOLHA UMA DAS OPÇÕES ACIMA : \n')) if menu_quest == 1: menu_registrar_entrada_saida() break elif menu_quest == 2: menu_entrada_saida() break elif menu_quest == 3: Estoque_Menu.menu_estoque() break else: print('\n!Erro') print('!Digite uma opção valída') except: print('\n!Erro') print('!Digite uma opção valída') def atualização_cadastral() -> dict : # Atualiza o armazenamento de informações de um produto mal registrado while True: quest: int = int(input('\nDigite o número de id do produto : ')) if quest in list_verifica_id: break elif quest != int: print('\n!Erro') print('Use apenas valores valídos') continue else: print('\n!Erro'), print('!Não encotrado') index:int = list_verifica_id.index(quest) # Acessa o index do produto selecionado class AtualizaProduto(): # Coleta e altera as informações do produto selecionado def __init__(self): self.__nome:str = input('Nome do produto : ') self.__quantidade:int = int(input('Quantidade : ')) self.tamanho = input('Tamanho do produto : ') self.cor:str = input('Cor do Produto : ') self.__data = input('Data de entrada do produto : ') self.__nRegistro:int = list_estoque[index]['INFO']['nRegistro'] list_estoque[index]['INFO']['nRegistro']:int = self.__nRegistro list_estoque[index]['INFO']['Nome']:str = self.__nome.title() list_estoque[index]['INFO']['Quantidade']:int = self.__quantidade list_estoque[index]['INFO']['Tamanho'] = self.tamanho list_estoque[index]['INFO']['Cor']:str = self.cor list_estoque[index]['INFO']['Data'] = self.__data def __repr__(self): AtualizaProduto() AtualizaProduto() print('\n', list_estoque[index]['INFO'], '- ATUALIZADO') def estoque() -> list: # Imprime todo o estoque disponível for c in list_estoque: print(c)
0.169784
0.451085
try: from pyspark import SparkContext, SparkConf,SQLContext from pyspark.sql.functions import to_date,lit,desc,col from pyspark.sql import Row from operator import add from server.main.utils import get_requireddataframe_fromcsv import sys except: print('error') def create_task(words): conf = SparkConf().setAppName('letter count') sc = SparkContext(conf=conf) seq = words.split() data = sc.parallelize(seq) counts = data.map(lambda word: (word, 1)).reduceByKey(add).collect() sc.stop() return dict(counts) def get_recent(spark_dataframe,given_date=None): result_data_frame = spark_dataframe.filter(to_date(spark_dataframe.dateAdded) == lit(given_date)).orderBy( spark_dataframe.dateAdded.desc()).limit(1) return result_data_frame def get_brand_count(spark_dataframe,given_date=None): result_data_frame = spark_dataframe.filter(to_date(spark_dataframe.dateAdded) == lit(given_date)).groupBy(spark_dataframe.brand).count().orderBy( col('count').desc()) return result_data_frame def get_by_color(spark_dataframe,given_color=None): result_data_frame = spark_dataframe.filter(spark_dataframe.colors.contains(given_color)).orderBy( spark_dataframe.dateAdded.desc()).limit(10) return result_data_frame def get_result(function,param=None): pandas_dataframe = get_requireddataframe_fromcsv('Latest_women_shoes.csv', ['id', 'brand', 'colors', 'dateAdded']) conf = SparkConf().setAppName('Women Catalog') sc = SparkContext(conf=conf) # df2 = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('sample.csv') #used pandas dataframe as using the above the file could not be located. sqlContext = SQLContext(sc) spark_dataframe = sqlContext.createDataFrame(pandas_dataframe) #data=spark_dataframe.select("*").toPandas() result_spark_dataframe=getattr(sys.modules[__name__], function)(spark_dataframe,param) result_python_dataframe = result_spark_dataframe.toPandas() result_dict = result_python_dataframe.to_dict('records') sc.stop() return result_dict """ def get_brandcount(given_date='2017-03-28'): pandas_dataframe = get_requireddataframe_fromcsv('Latest_women_shoes.csv', ['id', 'brand', 'colors', 'dateAdded']) conf = SparkConf().setAppName('Women Catalog') sc = SparkContext(conf=conf) # df2 = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('sample.csv') # used pandas dataframe as using the above the file could not be located. sqlContext = SQLContext(sc) spark_dataframe = sqlContext.createDataFrame(pandas_dataframe) # data=spark_dataframe.select("*").toPandas() result_python_dataframe = result_spark_dataframe.toPandas() result_dict = result_python_dataframe.to_dict() return result_dict """
services/web/project/server/main/tasks.py
try: from pyspark import SparkContext, SparkConf,SQLContext from pyspark.sql.functions import to_date,lit,desc,col from pyspark.sql import Row from operator import add from server.main.utils import get_requireddataframe_fromcsv import sys except: print('error') def create_task(words): conf = SparkConf().setAppName('letter count') sc = SparkContext(conf=conf) seq = words.split() data = sc.parallelize(seq) counts = data.map(lambda word: (word, 1)).reduceByKey(add).collect() sc.stop() return dict(counts) def get_recent(spark_dataframe,given_date=None): result_data_frame = spark_dataframe.filter(to_date(spark_dataframe.dateAdded) == lit(given_date)).orderBy( spark_dataframe.dateAdded.desc()).limit(1) return result_data_frame def get_brand_count(spark_dataframe,given_date=None): result_data_frame = spark_dataframe.filter(to_date(spark_dataframe.dateAdded) == lit(given_date)).groupBy(spark_dataframe.brand).count().orderBy( col('count').desc()) return result_data_frame def get_by_color(spark_dataframe,given_color=None): result_data_frame = spark_dataframe.filter(spark_dataframe.colors.contains(given_color)).orderBy( spark_dataframe.dateAdded.desc()).limit(10) return result_data_frame def get_result(function,param=None): pandas_dataframe = get_requireddataframe_fromcsv('Latest_women_shoes.csv', ['id', 'brand', 'colors', 'dateAdded']) conf = SparkConf().setAppName('Women Catalog') sc = SparkContext(conf=conf) # df2 = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('sample.csv') #used pandas dataframe as using the above the file could not be located. sqlContext = SQLContext(sc) spark_dataframe = sqlContext.createDataFrame(pandas_dataframe) #data=spark_dataframe.select("*").toPandas() result_spark_dataframe=getattr(sys.modules[__name__], function)(spark_dataframe,param) result_python_dataframe = result_spark_dataframe.toPandas() result_dict = result_python_dataframe.to_dict('records') sc.stop() return result_dict """ def get_brandcount(given_date='2017-03-28'): pandas_dataframe = get_requireddataframe_fromcsv('Latest_women_shoes.csv', ['id', 'brand', 'colors', 'dateAdded']) conf = SparkConf().setAppName('Women Catalog') sc = SparkContext(conf=conf) # df2 = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('sample.csv') # used pandas dataframe as using the above the file could not be located. sqlContext = SQLContext(sc) spark_dataframe = sqlContext.createDataFrame(pandas_dataframe) # data=spark_dataframe.select("*").toPandas() result_python_dataframe = result_spark_dataframe.toPandas() result_dict = result_python_dataframe.to_dict() return result_dict """
0.36557
0.282118
from entrenamiento.app.app import db from entrenamiento.models.base import BaseModel class Torneo(BaseModel): ''' Tiene toda la informacion sobre el tipo de resultado. Es importante tener en cuenta que esto se lo usa tanto para los torneos reales como para las practicas de torneos. :param int id: un numero autoincrementado. :param date cuando: la fecha de cuando fue el torneo en cuestion. :param int id_usuario: el id del usuario que va a cargar la informacion sobre como le fue en el torneo. :param int id_lugar: el identificador del lugar en donde fue el torneo. :param str tipo_de_torneo: identifica que tipo de torneo se esta haciendo. :param int puntaje_final_torneo: es la suma del puntaje de las 4 o 2 series del torneo. :param boolean fue_practica: si es True, entonces esto no fue un torneo en si, sino que fue una practica. :param str comentario: el comentario que quiere poner el usuario en cuestion. :param int posicion_classificacion: la posicion que termino el tirador teniendo en cuenta las X rondas del torneo. Esto no es para la posicion dentro si se gano medalla :param int posicion_eliminatorias: la posicion que se tiene en las eliminatorias. Basicamente esto es para ver si se termino 1, 2 o 3° ''' id = db.Column(db.Integer, primary_key=True) cuando = db.Column(db.Date, nullable=False) id_usuario = db.Column(db.Integer, db.ForeignKey('usuario.id', ondelete='CASCADE'), nullable=False) id_tipo_de_torneo = db.Column(db.Integer, db.ForeignKey('tipo_torneo.id'), nullable=False) id_lugar = db.Column(db.Integer, db.ForeignKey('lugar.id', ondelete='SET NULL')) id_arco = db.Column(db.Integer, db.ForeignKey('arco.id', ondelete='SET NULL')) comentario = db.Column(db.Text) puntaje_final_torneo = db.Column(db.Integer) fue_practica = db.Column(db.Boolean, nullable=False) posicion_classificacion = db.Column(db.Integer) posicion_eliminatoria = db.Column(db.Integer) class Ronda(BaseModel): ''' Tiene toda la informacion de una ronda del torneo. :param int id: un valor unico autoincrementado :param int id_torneo: el identificador del torneo a donde pertence la ronda en cuestion. :param int puntaje: el puntaje que se hizo en esta ronda. :param int distancia: la distancia a la que se tiro en este torneo. :param str foto: en caso de que no se quiera cargar toda la inforamcion de las series, tiene la foto de la planilla de resultado que se le entrego a los jueces ''' id = db.Column(db.Integer, primary_key=True) id_torneo = db.Column(db.Integer, db.ForeignKey('torneo.id', ondelete='CASCADE'), nullable=False) puntaje = db.Column(db.Integer) distancia = db.Column(db.Integer) foto_path = db.Column(db.Text) class Serie(BaseModel): ''' Tiene toda la informacion para una de las series del torneo. :param int id: un valor unico autoincrementado. :param boolean fue_de_practica: si es True, entonces esta serie fue una de las series de pracitca antes de empezar las series que se puntean :param int puntaje_flecha_X: el puntaje de la flecha X. El mismo tiene que ir desde el puntaje mas alto al puntaje mas bajo. Es decir, puntaje_flecha_1 tiene que ser el mas alto, y puntaje_flecha_6 el mas bajo. En caso de que una flecha haya sido mala, entonces se la pone como 0. :param int puntaje_final: el puntaje de las 6 flechas. ''' id = db.Column(db.Integer, primary_key=True) id_ronda = db.Column(db.Integer, db.ForeignKey('ronda.id', ondelete='CASCADE'), nullable=False) fue_de_practica = db.Column(db.Boolean) puntaje_flecha_1 = db.Column(db.Integer) puntaje_flecha_2 = db.Column(db.Integer) puntaje_flecha_3 = db.Column(db.Integer) puntaje_flecha_4 = db.Column(db.Integer) puntaje_flecha_5 = db.Column(db.Integer) puntaje_flecha_6 = db.Column(db.Integer) puntaje_total = db.Column(db.Integer)
entrenamiento/models/torneo.py
from entrenamiento.app.app import db from entrenamiento.models.base import BaseModel class Torneo(BaseModel): ''' Tiene toda la informacion sobre el tipo de resultado. Es importante tener en cuenta que esto se lo usa tanto para los torneos reales como para las practicas de torneos. :param int id: un numero autoincrementado. :param date cuando: la fecha de cuando fue el torneo en cuestion. :param int id_usuario: el id del usuario que va a cargar la informacion sobre como le fue en el torneo. :param int id_lugar: el identificador del lugar en donde fue el torneo. :param str tipo_de_torneo: identifica que tipo de torneo se esta haciendo. :param int puntaje_final_torneo: es la suma del puntaje de las 4 o 2 series del torneo. :param boolean fue_practica: si es True, entonces esto no fue un torneo en si, sino que fue una practica. :param str comentario: el comentario que quiere poner el usuario en cuestion. :param int posicion_classificacion: la posicion que termino el tirador teniendo en cuenta las X rondas del torneo. Esto no es para la posicion dentro si se gano medalla :param int posicion_eliminatorias: la posicion que se tiene en las eliminatorias. Basicamente esto es para ver si se termino 1, 2 o 3° ''' id = db.Column(db.Integer, primary_key=True) cuando = db.Column(db.Date, nullable=False) id_usuario = db.Column(db.Integer, db.ForeignKey('usuario.id', ondelete='CASCADE'), nullable=False) id_tipo_de_torneo = db.Column(db.Integer, db.ForeignKey('tipo_torneo.id'), nullable=False) id_lugar = db.Column(db.Integer, db.ForeignKey('lugar.id', ondelete='SET NULL')) id_arco = db.Column(db.Integer, db.ForeignKey('arco.id', ondelete='SET NULL')) comentario = db.Column(db.Text) puntaje_final_torneo = db.Column(db.Integer) fue_practica = db.Column(db.Boolean, nullable=False) posicion_classificacion = db.Column(db.Integer) posicion_eliminatoria = db.Column(db.Integer) class Ronda(BaseModel): ''' Tiene toda la informacion de una ronda del torneo. :param int id: un valor unico autoincrementado :param int id_torneo: el identificador del torneo a donde pertence la ronda en cuestion. :param int puntaje: el puntaje que se hizo en esta ronda. :param int distancia: la distancia a la que se tiro en este torneo. :param str foto: en caso de que no se quiera cargar toda la inforamcion de las series, tiene la foto de la planilla de resultado que se le entrego a los jueces ''' id = db.Column(db.Integer, primary_key=True) id_torneo = db.Column(db.Integer, db.ForeignKey('torneo.id', ondelete='CASCADE'), nullable=False) puntaje = db.Column(db.Integer) distancia = db.Column(db.Integer) foto_path = db.Column(db.Text) class Serie(BaseModel): ''' Tiene toda la informacion para una de las series del torneo. :param int id: un valor unico autoincrementado. :param boolean fue_de_practica: si es True, entonces esta serie fue una de las series de pracitca antes de empezar las series que se puntean :param int puntaje_flecha_X: el puntaje de la flecha X. El mismo tiene que ir desde el puntaje mas alto al puntaje mas bajo. Es decir, puntaje_flecha_1 tiene que ser el mas alto, y puntaje_flecha_6 el mas bajo. En caso de que una flecha haya sido mala, entonces se la pone como 0. :param int puntaje_final: el puntaje de las 6 flechas. ''' id = db.Column(db.Integer, primary_key=True) id_ronda = db.Column(db.Integer, db.ForeignKey('ronda.id', ondelete='CASCADE'), nullable=False) fue_de_practica = db.Column(db.Boolean) puntaje_flecha_1 = db.Column(db.Integer) puntaje_flecha_2 = db.Column(db.Integer) puntaje_flecha_3 = db.Column(db.Integer) puntaje_flecha_4 = db.Column(db.Integer) puntaje_flecha_5 = db.Column(db.Integer) puntaje_flecha_6 = db.Column(db.Integer) puntaje_total = db.Column(db.Integer)
0.520984
0.440409
from fastapi import APIRouter, HTTPException, Depends from pymongo.client_session import ClientSession from autologging import logged from app.api.deps import get_session from app.db.operations import insert_one, update_one from app.schemas.response import InsertOneResponse, UpdateOneResponse from app.schemas.usage import AttemptStart, CheckpointStart, CheckpointEnd, AttemptEnd router = APIRouter() @logged class Usage: # Post the start attempt @router.post("/attempt/start", status_code=201, response_model=InsertOneResponse) async def post_start_attempt( attempt: AttemptStart, session: ClientSession = Depends(get_session) ): Usage.__log.info(attempt.dict()) return await insert_one( "usageStats", "journeyMap", attempt.dict(), session=session ) # Update with checkpoint start @router.put("/checkpoint/start", response_model=UpdateOneResponse) async def update_checkpoint( checkpoint: CheckpointStart, session: ClientSession = Depends(get_session) ): update_dict = checkpoint.dict() update_query = {"attemptId": update_dict.pop("attemptId")} update = {"$push": {"checkpoints": update_dict}} custom_exception = HTTPException( status_code=404, detail="Unable to find matching attempt" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, session=session, custom_exception=custom_exception, ) # Update with checkpoint end @router.put("/checkpoint/end", response_model=UpdateOneResponse) async def update_checkpoint( checkpoint: CheckpointEnd, session: ClientSession = Depends(get_session) ): update_query = { "attemptId": checkpoint.attemptId, } update = {"$set": {"checkpoints.$[cp].end": checkpoint.end}} array_filters = [{"cp.description": checkpoint.description}] custom_exception = HTTPException( status_code=404, detail="Unable to find matching checkpoint" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, array_filters=array_filters, session=session, custom_exception=custom_exception, ) # Update with attempt end @router.put("/attempt/end", response_model=UpdateOneResponse) async def update_checkpoint( attempt: AttemptEnd, session: ClientSession = Depends(get_session) ): update_dict = attempt.dict() update_query = {"attemptId": update_dict.pop("attemptId")} update = {"$set": update_dict} custom_exception = HTTPException( status_code=404, detail="Unable to find matching attempt" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, session=session, custom_exception=custom_exception, )
backend/app/api/endpoints/usage.py
from fastapi import APIRouter, HTTPException, Depends from pymongo.client_session import ClientSession from autologging import logged from app.api.deps import get_session from app.db.operations import insert_one, update_one from app.schemas.response import InsertOneResponse, UpdateOneResponse from app.schemas.usage import AttemptStart, CheckpointStart, CheckpointEnd, AttemptEnd router = APIRouter() @logged class Usage: # Post the start attempt @router.post("/attempt/start", status_code=201, response_model=InsertOneResponse) async def post_start_attempt( attempt: AttemptStart, session: ClientSession = Depends(get_session) ): Usage.__log.info(attempt.dict()) return await insert_one( "usageStats", "journeyMap", attempt.dict(), session=session ) # Update with checkpoint start @router.put("/checkpoint/start", response_model=UpdateOneResponse) async def update_checkpoint( checkpoint: CheckpointStart, session: ClientSession = Depends(get_session) ): update_dict = checkpoint.dict() update_query = {"attemptId": update_dict.pop("attemptId")} update = {"$push": {"checkpoints": update_dict}} custom_exception = HTTPException( status_code=404, detail="Unable to find matching attempt" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, session=session, custom_exception=custom_exception, ) # Update with checkpoint end @router.put("/checkpoint/end", response_model=UpdateOneResponse) async def update_checkpoint( checkpoint: CheckpointEnd, session: ClientSession = Depends(get_session) ): update_query = { "attemptId": checkpoint.attemptId, } update = {"$set": {"checkpoints.$[cp].end": checkpoint.end}} array_filters = [{"cp.description": checkpoint.description}] custom_exception = HTTPException( status_code=404, detail="Unable to find matching checkpoint" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, array_filters=array_filters, session=session, custom_exception=custom_exception, ) # Update with attempt end @router.put("/attempt/end", response_model=UpdateOneResponse) async def update_checkpoint( attempt: AttemptEnd, session: ClientSession = Depends(get_session) ): update_dict = attempt.dict() update_query = {"attemptId": update_dict.pop("attemptId")} update = {"$set": update_dict} custom_exception = HTTPException( status_code=404, detail="Unable to find matching attempt" ) Usage.__log.info(update) return await update_one( "usageStats", "journeyMap", update_query, update, session=session, custom_exception=custom_exception, )
0.731346
0.098555
import logging import os import shutil import subprocess # nosec import uuid from tempfile import mkdtemp from textwrap import fill from typing import Iterable, Generator, Optional, Sequence from pkg_resources import resource_string import markdown from jinja2 import Template from publish import __version__ as package_version from publish.book import Book, Chapter from publish.substitution import Substitution, apply_substitutions LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) SUPPORTED_EBOOKCONVERT_ATTRIBUTES = ( 'author_sort', 'authors', 'book_producer', 'comments', 'cover', 'isbn', 'language', 'pubdate', 'publisher', 'rating', 'series', 'series_index', 'tags', 'title' ) class HtmlOutput: """Turns a Book object and its chapters into an html document. Args: path: The output path. **kwargs: Any other attribute of this class. (see Attributes below) Attributes: path (str): The output path. stylesheet (str): The path to the style sheet. force_publish (bool): Determines wether to force publish all chapters. If set to true, all chapters of the book will be published no matter how the chapters are configured. Defaults to False. """ def __init__(self, path: str, **kwargs): """Initializes a new instance of the :class:`HtmlOutput` class. """ self.path = path self.stylesheet = kwargs.pop('stylesheet', None) self.force_publish = kwargs.pop('force_publish', False) def make(self, book: Book, substitutions: Optional[Iterable[Substitution]] = None): """Makes the Output for the provided book and substitutions. Args: book: The book. substitutions: The substitutions. """ LOG.info('Making HtmlOutput ...') if not substitutions: substitutions = [] html_document = self._get_html_document(book, substitutions) with open(self.path, 'w') as file: file.write(html_document) LOG.info('... HtmlOutput finished') def get_chapters_to_be_published(self, chapters: Iterable[Chapter] ) -> Iterable[Chapter]: """Gets the list of chapters to be published based on each chapters `publish` attribute. If the outputs `force_publish` override is set to true, all chapters will be published regardless of their individual `publish` attributes. Returns: The list of chapters to be published. """ if self.force_publish: return chapters return list(filter(lambda c: c.publish is True, chapters)) def _get_css(self) -> str: """Gets the css from the css file specified in stylesheet as a string. Returns: The css from the css file specified in stylesheet as a string. """ if not self.stylesheet: return '' css_path = os.path.join(os.getcwd(), self.stylesheet) LOG.info('Collecting stylesheet ...') with open(css_path, 'r') as file: css = file.read() return css if css else '' def _get_html_document(self, book: Book, substitutions: Iterable[Substitution] ) -> str: """Takes a book, renders it to html, applying the list of substitutions in the process and returns the finished html document as a string. Args: book: The book. substitutions: The list of substitutions. Returns: The html document as a string. """ html_content = self._get_html_content(book.chapters, substitutions) html_document = _apply_template(html_content=html_content, title=book.title, css=self._get_css(), language=book.language) return html_document def _get_html_content(self, chapters: Iterable[Chapter], substitutions: Iterable[Substitution]) -> str: """Gets the content of the provided list of chapters as as an html string. The list of substitutions is applied to the markdown content before it is rendered to html. The order of the chapters is preserved. The resulting html string does not include a head or body, only the chapters markdown turned into html. Args: chapters: The list of chapters. substitutions: The list of substitutions. Returns: The content of the provided list of chapters as an html string. """ markdown_ = self._get_markdown_content(chapters) markdown_ = apply_substitutions( markdown_, substitutions) LOG.info('Rendering markdown to html ...') return markdown.markdown(markdown_) def _get_markdown_content(self, chapters: Iterable[Chapter]) -> str: """Gets the markdown content of the provided list of chapters concatenated into a single string. The order of the chapters is preserved. Args: chapters: The list of chapters. Returns: The markdown content of the list of chapters concatenated into a single string. """ markdown_ = [] md_paragraph_sep = '\n\n' if not chapters: raise NoChaptersFoundError('Your book contains no chapters.') chapters_to_publish = self.get_chapters_to_be_published(chapters) if not chapters_to_publish: raise NoChaptersFoundError('None of your chapters are set to be' 'published.') LOG.info('Collecting chapters ...') for chapter in chapters_to_publish: with open(chapter.src, 'r') as file: markdown_.append(file.read()) return md_paragraph_sep.join(markdown_) class EbookConvertOutput(HtmlOutput): """Turns Book objects and its chapters into an ebook using Kavid Goyals ebookconvert command line tool. .. todo:: document format of ebookconvert_params -> {'key':'value'} or object.key = value Args: path: The output path. **kwargs: Any other attribute of this class. (see Attributes below) Attributes: ebookconvert_params (List[str]): An optional list of additional command line arguments that will be passed to ebookconvert. path (str): The output path. stylesheet (str): The path to the style sheet. force_publish (bool): Determines wether to force publish all chapters. If set to true, all chapters of the book will be published no matter how the chapters are configured. Defaults to False. """ def __init__(self, path: str, **kwargs): """Initializes a new instance of the :class:`EbookConvertOutput` class. """ super().__init__(path, **kwargs) self.ebookconvert_params = kwargs.pop('ebookconvert_params', []) def make(self, book: Book, substitutions: Optional[Iterable[Substitution]] = None): """Makes an ebook from the provided book object and the markdown chapters specified therein. Substitutions are applied to the raw markdown before the markdown is processed. Args: book: The book. substitutions: The list of substitutions. """ LOG.info('Making EbookConvertOutput ...') if not book: raise AttributeError("book must not be None") if not substitutions: substitutions = [] temp_directory = mkdtemp() # mkstmp and NamedTemporaryFile won't work, because the html file # will be kept open by EbookConvertOutput with exclusive access, # which means ebook-convert can't read the html to create the epub. # -> ebook-convert fails with 'Permission denied'. try: temp_path = os.path.join( temp_directory, str(uuid.uuid4()) + '.html') html_document = self._get_html_document(book, substitutions) with open(temp_path, 'w') as file: file.write(html_document) call_params = _get_ebook_convert_params(book, input_path=temp_path, output_path=self.path, additional_params=self.ebookconvert_params) LOG.info('Calling ebook-convert ...') try: subprocess.call(call_params, shell=False) # nosec except FileNotFoundError: LOG.error( fill('Could not find ebook-convert. Please install calibre if you want to ' 'use EbookconvertOutput and make sure ebook-convert is accessible ' 'through the PATH variable.')) return LOG.info('... EbookConvertOutput finished') finally: shutil.rmtree(temp_directory) def _get_ebook_convert_params(book: Book, input_path: str, output_path: str, additional_params: Optional[Iterable[str]] = None ) -> Sequence[str]: """Gets the call params for the ebookconvert commandline. The book's attributes are translated into ebookconvert metadata commandline options while any additional options present in EbookConvertOutput.ebookconvert_params are appended to the call params as is. Args: book: The book object. input_path: The path the html file that will be passed to ebookconvert. output_path: The output path. """ if not additional_params: additional_params = [] call_params = [ 'ebook-convert', input_path, output_path ] call_params.extend(_yield_attributes_as_params(book)) call_params.extend(additional_params) return call_params def _apply_template(html_content: str, title: str, css: str, language: str) -> str: """Renders the html content, title, css and document language into the jinja2 formatted template and returns the resulting html document. Args: html_content: The html content gets inserted into the {{ content }} of the template. title: The title gets inserted into the {{ title }} of the template. css: The css gets inserted into the {{ css }} of the template. language: The language gets inserted into the {{ language }} of the template. Returns: The html document. """ template = resource_string(__name__, 'template.jinja') \ .decode('utf-8') \ .replace('\r\n', '\n') # resource_string opens the file as bytes, which means that we # have to decode to utf-8. The replace is necessary because # resource_string, instead of open, does not automatically # strip \r\n down to \n on windows systems. Leaving \r\n as is # would produce double line breaks when writing the resulting string # back to disc, thus we have to do the replacement ourselves, too. return Template(template).render(content=html_content, title=title, css=css, language=language, package_version=package_version) def _yield_attributes_as_params(object_) -> Generator[str, None, None]: """Takes an object or dictionary and returns a generator yielding all attributes that can be processed by the ebookconvert command line as a parameter array. Args: object_: An object or dictionary. Returns: A generator yielding all attributes of the object supported by ebookconvert. """ # This way the book can contain attributes not supported by ebookconvert # (or any other specific output that follows this explicit pattern) for attr_name in SUPPORTED_EBOOKCONVERT_ATTRIBUTES: if hasattr(object_, attr_name): attr = getattr(object_, attr_name) else: try: attr = object_[attr_name] except (TypeError, KeyError): continue if not attr: continue attr = str(attr) if attr and not attr.isspace(): yield '--{0}={1}'.format(attr_name, attr) class NoChaptersFoundError(Exception): """No chapters found."""
publish/output.py
import logging import os import shutil import subprocess # nosec import uuid from tempfile import mkdtemp from textwrap import fill from typing import Iterable, Generator, Optional, Sequence from pkg_resources import resource_string import markdown from jinja2 import Template from publish import __version__ as package_version from publish.book import Book, Chapter from publish.substitution import Substitution, apply_substitutions LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) SUPPORTED_EBOOKCONVERT_ATTRIBUTES = ( 'author_sort', 'authors', 'book_producer', 'comments', 'cover', 'isbn', 'language', 'pubdate', 'publisher', 'rating', 'series', 'series_index', 'tags', 'title' ) class HtmlOutput: """Turns a Book object and its chapters into an html document. Args: path: The output path. **kwargs: Any other attribute of this class. (see Attributes below) Attributes: path (str): The output path. stylesheet (str): The path to the style sheet. force_publish (bool): Determines wether to force publish all chapters. If set to true, all chapters of the book will be published no matter how the chapters are configured. Defaults to False. """ def __init__(self, path: str, **kwargs): """Initializes a new instance of the :class:`HtmlOutput` class. """ self.path = path self.stylesheet = kwargs.pop('stylesheet', None) self.force_publish = kwargs.pop('force_publish', False) def make(self, book: Book, substitutions: Optional[Iterable[Substitution]] = None): """Makes the Output for the provided book and substitutions. Args: book: The book. substitutions: The substitutions. """ LOG.info('Making HtmlOutput ...') if not substitutions: substitutions = [] html_document = self._get_html_document(book, substitutions) with open(self.path, 'w') as file: file.write(html_document) LOG.info('... HtmlOutput finished') def get_chapters_to_be_published(self, chapters: Iterable[Chapter] ) -> Iterable[Chapter]: """Gets the list of chapters to be published based on each chapters `publish` attribute. If the outputs `force_publish` override is set to true, all chapters will be published regardless of their individual `publish` attributes. Returns: The list of chapters to be published. """ if self.force_publish: return chapters return list(filter(lambda c: c.publish is True, chapters)) def _get_css(self) -> str: """Gets the css from the css file specified in stylesheet as a string. Returns: The css from the css file specified in stylesheet as a string. """ if not self.stylesheet: return '' css_path = os.path.join(os.getcwd(), self.stylesheet) LOG.info('Collecting stylesheet ...') with open(css_path, 'r') as file: css = file.read() return css if css else '' def _get_html_document(self, book: Book, substitutions: Iterable[Substitution] ) -> str: """Takes a book, renders it to html, applying the list of substitutions in the process and returns the finished html document as a string. Args: book: The book. substitutions: The list of substitutions. Returns: The html document as a string. """ html_content = self._get_html_content(book.chapters, substitutions) html_document = _apply_template(html_content=html_content, title=book.title, css=self._get_css(), language=book.language) return html_document def _get_html_content(self, chapters: Iterable[Chapter], substitutions: Iterable[Substitution]) -> str: """Gets the content of the provided list of chapters as as an html string. The list of substitutions is applied to the markdown content before it is rendered to html. The order of the chapters is preserved. The resulting html string does not include a head or body, only the chapters markdown turned into html. Args: chapters: The list of chapters. substitutions: The list of substitutions. Returns: The content of the provided list of chapters as an html string. """ markdown_ = self._get_markdown_content(chapters) markdown_ = apply_substitutions( markdown_, substitutions) LOG.info('Rendering markdown to html ...') return markdown.markdown(markdown_) def _get_markdown_content(self, chapters: Iterable[Chapter]) -> str: """Gets the markdown content of the provided list of chapters concatenated into a single string. The order of the chapters is preserved. Args: chapters: The list of chapters. Returns: The markdown content of the list of chapters concatenated into a single string. """ markdown_ = [] md_paragraph_sep = '\n\n' if not chapters: raise NoChaptersFoundError('Your book contains no chapters.') chapters_to_publish = self.get_chapters_to_be_published(chapters) if not chapters_to_publish: raise NoChaptersFoundError('None of your chapters are set to be' 'published.') LOG.info('Collecting chapters ...') for chapter in chapters_to_publish: with open(chapter.src, 'r') as file: markdown_.append(file.read()) return md_paragraph_sep.join(markdown_) class EbookConvertOutput(HtmlOutput): """Turns Book objects and its chapters into an ebook using Kavid Goyals ebookconvert command line tool. .. todo:: document format of ebookconvert_params -> {'key':'value'} or object.key = value Args: path: The output path. **kwargs: Any other attribute of this class. (see Attributes below) Attributes: ebookconvert_params (List[str]): An optional list of additional command line arguments that will be passed to ebookconvert. path (str): The output path. stylesheet (str): The path to the style sheet. force_publish (bool): Determines wether to force publish all chapters. If set to true, all chapters of the book will be published no matter how the chapters are configured. Defaults to False. """ def __init__(self, path: str, **kwargs): """Initializes a new instance of the :class:`EbookConvertOutput` class. """ super().__init__(path, **kwargs) self.ebookconvert_params = kwargs.pop('ebookconvert_params', []) def make(self, book: Book, substitutions: Optional[Iterable[Substitution]] = None): """Makes an ebook from the provided book object and the markdown chapters specified therein. Substitutions are applied to the raw markdown before the markdown is processed. Args: book: The book. substitutions: The list of substitutions. """ LOG.info('Making EbookConvertOutput ...') if not book: raise AttributeError("book must not be None") if not substitutions: substitutions = [] temp_directory = mkdtemp() # mkstmp and NamedTemporaryFile won't work, because the html file # will be kept open by EbookConvertOutput with exclusive access, # which means ebook-convert can't read the html to create the epub. # -> ebook-convert fails with 'Permission denied'. try: temp_path = os.path.join( temp_directory, str(uuid.uuid4()) + '.html') html_document = self._get_html_document(book, substitutions) with open(temp_path, 'w') as file: file.write(html_document) call_params = _get_ebook_convert_params(book, input_path=temp_path, output_path=self.path, additional_params=self.ebookconvert_params) LOG.info('Calling ebook-convert ...') try: subprocess.call(call_params, shell=False) # nosec except FileNotFoundError: LOG.error( fill('Could not find ebook-convert. Please install calibre if you want to ' 'use EbookconvertOutput and make sure ebook-convert is accessible ' 'through the PATH variable.')) return LOG.info('... EbookConvertOutput finished') finally: shutil.rmtree(temp_directory) def _get_ebook_convert_params(book: Book, input_path: str, output_path: str, additional_params: Optional[Iterable[str]] = None ) -> Sequence[str]: """Gets the call params for the ebookconvert commandline. The book's attributes are translated into ebookconvert metadata commandline options while any additional options present in EbookConvertOutput.ebookconvert_params are appended to the call params as is. Args: book: The book object. input_path: The path the html file that will be passed to ebookconvert. output_path: The output path. """ if not additional_params: additional_params = [] call_params = [ 'ebook-convert', input_path, output_path ] call_params.extend(_yield_attributes_as_params(book)) call_params.extend(additional_params) return call_params def _apply_template(html_content: str, title: str, css: str, language: str) -> str: """Renders the html content, title, css and document language into the jinja2 formatted template and returns the resulting html document. Args: html_content: The html content gets inserted into the {{ content }} of the template. title: The title gets inserted into the {{ title }} of the template. css: The css gets inserted into the {{ css }} of the template. language: The language gets inserted into the {{ language }} of the template. Returns: The html document. """ template = resource_string(__name__, 'template.jinja') \ .decode('utf-8') \ .replace('\r\n', '\n') # resource_string opens the file as bytes, which means that we # have to decode to utf-8. The replace is necessary because # resource_string, instead of open, does not automatically # strip \r\n down to \n on windows systems. Leaving \r\n as is # would produce double line breaks when writing the resulting string # back to disc, thus we have to do the replacement ourselves, too. return Template(template).render(content=html_content, title=title, css=css, language=language, package_version=package_version) def _yield_attributes_as_params(object_) -> Generator[str, None, None]: """Takes an object or dictionary and returns a generator yielding all attributes that can be processed by the ebookconvert command line as a parameter array. Args: object_: An object or dictionary. Returns: A generator yielding all attributes of the object supported by ebookconvert. """ # This way the book can contain attributes not supported by ebookconvert # (or any other specific output that follows this explicit pattern) for attr_name in SUPPORTED_EBOOKCONVERT_ATTRIBUTES: if hasattr(object_, attr_name): attr = getattr(object_, attr_name) else: try: attr = object_[attr_name] except (TypeError, KeyError): continue if not attr: continue attr = str(attr) if attr and not attr.isspace(): yield '--{0}={1}'.format(attr_name, attr) class NoChaptersFoundError(Exception): """No chapters found."""
0.718397
0.207496
import pytest from clean.entities.token import UserToken from clean.auth.abs import DecodeToken from clean.auth.decorator import DecoratorBuilder from clean.exceptions import AuthException class VerifyTokenAuth(DecodeToken): def get_token(self): raw = self.raw_token.get('token', None) if raw is None: raise AuthException('null token') return raw def verify(self, token: str): return UserToken('crl', '<EMAIL>', photo_url='', scopes={'bar': 'foo'}, app_meta={'bar': 'foo'}).to_dict() def test_create_decorator(): def token_finder(): return {'token': 'bar'} db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() usr_token = result['user_token'] assert res is True assert usr_token is not None assert usr_token['username'] == 'crl' def test_auth_exception(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect() def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() assert res == {'error': 'token not found'} def test_verify_class_is_subclass_of_decode_token(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() assert callable(protect) is True def test_verify_class_is_not_subclass_of_decode_token(): def token_finder(): return None class Foo: pass with pytest.raises(AttributeError): DecoratorBuilder(verify_class=Foo, token_finder_func=token_finder) def test_token_finder_func_is_not_callable(): token = {} with pytest.raises(AttributeError): DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token) def test_auth_exception_with_invalid_scopes(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}, rule={'path': 'scopes.bar', 'op': 'eq1', 'value': 'foo'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() assert res == {'error': 'token not found'} def test_auth_with_valid_scopes(): def token_finder(): return {'token': 'bar'} db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}, rule={'path': 'scopes.bar', 'op': 'eq', 'value': 'foo'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() usr_token = result['user_token'] assert res is True assert usr_token is not None assert usr_token['username'] == 'crl'
tests/clean/auth/test_decorator_builder.py
import pytest from clean.entities.token import UserToken from clean.auth.abs import DecodeToken from clean.auth.decorator import DecoratorBuilder from clean.exceptions import AuthException class VerifyTokenAuth(DecodeToken): def get_token(self): raw = self.raw_token.get('token', None) if raw is None: raise AuthException('null token') return raw def verify(self, token: str): return UserToken('crl', '<EMAIL>', photo_url='', scopes={'bar': 'foo'}, app_meta={'bar': 'foo'}).to_dict() def test_create_decorator(): def token_finder(): return {'token': 'bar'} db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() usr_token = result['user_token'] assert res is True assert usr_token is not None assert usr_token['username'] == 'crl' def test_auth_exception(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect() def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() assert res == {'error': 'token not found'} def test_verify_class_is_subclass_of_decode_token(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() assert callable(protect) is True def test_verify_class_is_not_subclass_of_decode_token(): def token_finder(): return None class Foo: pass with pytest.raises(AttributeError): DecoratorBuilder(verify_class=Foo, token_finder_func=token_finder) def test_token_finder_func_is_not_callable(): token = {} with pytest.raises(AttributeError): DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token) def test_auth_exception_with_invalid_scopes(): def token_finder(): return None db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}, rule={'path': 'scopes.bar', 'op': 'eq1', 'value': 'foo'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() assert res == {'error': 'token not found'} def test_auth_with_valid_scopes(): def token_finder(): return {'token': 'bar'} db = DecoratorBuilder(verify_class=VerifyTokenAuth, token_finder_func=token_finder) protect = db.create() result = dict() @protect(user={'req': 'user'}, rule={'path': 'scopes.bar', 'op': 'eq', 'value': 'foo'}) def my_endpoint(user_token, *args, **kwargs): result['user_token'] = user_token return True res = my_endpoint() usr_token = result['user_token'] assert res is True assert usr_token is not None assert usr_token['username'] == 'crl'
0.577853
0.224682
from flask import Flask, json, render_template from threading import Thread from flask_socketio import SocketIO from graphqlclient import GraphQLClient import serial, time, serial.tools.list_ports, datetime, socket app = Flask(__name__) app.config['SECRET_KEY'] = 'SECRET!' socketio = SocketIO(app) uuid_last = '' data = '' connexion_genius = GraphQLClient('https://##.###.##/') connexion_genius.inject_token('Bearer ####','Authorization') REMOTE_SERVER = "##.###.##" @app.route('/') def index(): return render_template('index.html') def is_connected(): try: host = socket.gethostbyname(REMOTE_SERVER) socket.create_connection((host, 80), 2) return True except: pass return False def getprofilewithbadge(badge): tmp = connexion_genius.execute('''{ profiles(where:{badge:"''' + badge + '''"}){ firstName lastName } } ''') return tmp def sethello(badge): tmp = connexion_genius.execute('''mutation{terminalHello(data:{badge:"''' + badge + '''",timeOfArrival:"''' + str(datetime.datetime.now().isoformat()) + '''"}){status}}''') return tmp class SerialRead(Thread): global j def __init__(self): Thread.__init__(self) ports = list(serial.tools.list_ports.comports()) for p in ports: if "Arduino" in p[1] or "ttyACM0" in p[1]: print("Arduino detecte sur le port : ", p[0]) self.serial = serial.Serial(str(p[0]), 9600, timeout=1) socketio.emit('Internet', {'internet': True}) def init_serial(self): ports = list(serial.tools.list_ports.comports()) self.serial.close() for p in ports: if "Arduino" in p[1] or "ttyACM0" in p[1]: print("Arduino detecte sur le port : ", p[0]) self.serial = serial.Serial(str(p[0]), 9600, timeout=1) socketio.emit('Internet', {'internet': True}) self.run() def run(self): global uuid_last while True: try: if self.serial is not None: data = self.serial.readline().strip(b'\n\r') try: if is_connected(): j = json.loads(data.decode('UTF-8')) socketio.emit('Internet', {'internet': True}) if "ESTIAM" in j['uuid']: if uuid_last != j['uuid']: uuid_last = j['uuid'] try: reponse = json.loads(sethello(uuid_last)) try: if len(reponse['errors']) > 0: socketio.emit('CardFound', {'error':True,'user': None, 'late':False}) except: if reponse['data']['terminalHello']['status'] == "OK": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "ALREADYBADGED": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "NO_DATE": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "UNKNOWN_CARD": socketio.emit('CardFound', {'error':True,'user':False,'late':False}) if reponse['data']['terminalHello']['status'] == "FAILED_SYS_ERROR": socketio.emit('CardFound', {'error': True, 'user': False, 'late': False}) except: continue else: socketio.emit('Internet', {'internet': False}) except: continue except: socketio.emit('Internet', {'internet': False}) print("La liaison serie ne peut etre etablie") time.sleep(1) self.init_serial() def first(self): self.run() if __name__ == '__main__': ThreadSerial = SerialRead() ThreadSerial.start() socketio.run(app,host='0.0.0.0',port=8000)
app.py
from flask import Flask, json, render_template from threading import Thread from flask_socketio import SocketIO from graphqlclient import GraphQLClient import serial, time, serial.tools.list_ports, datetime, socket app = Flask(__name__) app.config['SECRET_KEY'] = 'SECRET!' socketio = SocketIO(app) uuid_last = '' data = '' connexion_genius = GraphQLClient('https://##.###.##/') connexion_genius.inject_token('Bearer ####','Authorization') REMOTE_SERVER = "##.###.##" @app.route('/') def index(): return render_template('index.html') def is_connected(): try: host = socket.gethostbyname(REMOTE_SERVER) socket.create_connection((host, 80), 2) return True except: pass return False def getprofilewithbadge(badge): tmp = connexion_genius.execute('''{ profiles(where:{badge:"''' + badge + '''"}){ firstName lastName } } ''') return tmp def sethello(badge): tmp = connexion_genius.execute('''mutation{terminalHello(data:{badge:"''' + badge + '''",timeOfArrival:"''' + str(datetime.datetime.now().isoformat()) + '''"}){status}}''') return tmp class SerialRead(Thread): global j def __init__(self): Thread.__init__(self) ports = list(serial.tools.list_ports.comports()) for p in ports: if "Arduino" in p[1] or "ttyACM0" in p[1]: print("Arduino detecte sur le port : ", p[0]) self.serial = serial.Serial(str(p[0]), 9600, timeout=1) socketio.emit('Internet', {'internet': True}) def init_serial(self): ports = list(serial.tools.list_ports.comports()) self.serial.close() for p in ports: if "Arduino" in p[1] or "ttyACM0" in p[1]: print("Arduino detecte sur le port : ", p[0]) self.serial = serial.Serial(str(p[0]), 9600, timeout=1) socketio.emit('Internet', {'internet': True}) self.run() def run(self): global uuid_last while True: try: if self.serial is not None: data = self.serial.readline().strip(b'\n\r') try: if is_connected(): j = json.loads(data.decode('UTF-8')) socketio.emit('Internet', {'internet': True}) if "ESTIAM" in j['uuid']: if uuid_last != j['uuid']: uuid_last = j['uuid'] try: reponse = json.loads(sethello(uuid_last)) try: if len(reponse['errors']) > 0: socketio.emit('CardFound', {'error':True,'user': None, 'late':False}) except: if reponse['data']['terminalHello']['status'] == "OK": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "ALREADYBADGED": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "NO_DATE": profile = json.loads(getprofilewithbadge(uuid_last)) socketio.emit('CardFound', {'error':False,'user': {'firstName': profile['data']['profiles'][0]['firstName'],'lastName': profile['data']['profiles'][0]['lastName'],'late': None}, 'late':False}) if reponse['data']['terminalHello']['status'] == "UNKNOWN_CARD": socketio.emit('CardFound', {'error':True,'user':False,'late':False}) if reponse['data']['terminalHello']['status'] == "FAILED_SYS_ERROR": socketio.emit('CardFound', {'error': True, 'user': False, 'late': False}) except: continue else: socketio.emit('Internet', {'internet': False}) except: continue except: socketio.emit('Internet', {'internet': False}) print("La liaison serie ne peut etre etablie") time.sleep(1) self.init_serial() def first(self): self.run() if __name__ == '__main__': ThreadSerial = SerialRead() ThreadSerial.start() socketio.run(app,host='0.0.0.0',port=8000)
0.254602
0.086632
from pero.properties import * from pero import Legend, LegendBox from .. enums import * from . graphics import InGraphics, OutGraphics class OutLegend(OutGraphics): """ OutLegend provides a wrapper for the pero.LegendBox glyph to draw the chart legend outside the main data frame. Properties: items: (pero.Legend,), None or UNDEF Specifies a collection of legend items to draw. static: bool Specifies whether the legend items are given by user directly (True) or whether they should be retrieved automatically from parent chart (False). position: pero.POSITION_LRTB Specifies the legend position within a chart as any item from the pero.POSITION_LRTB enum. orientation: pero.ORIENTATION Specifies the legend orientation as any item from the pero.ORIENTATION enum. margin: int, float, (int,), (float,) or UNDEF Specifies the space around the legend box as a single value or values for individual sides starting from top. padding: int, float, (int,), (float,) or UNDEF Specifies the inner space of the legend box as a single value or values for individual sides starting from top. spacing: int or float Specifies the additional space between legend items. radius: int, float, (int,), (float,) or UNDEF Specifies the corner radius of the legend box as a single value or values for individual corners starting from top-left. line properties: Includes pero.LineProperties to specify the legend box outline. fill properties: Includes pero.FillProperties to specify the legend box fill. """ items = TupleProperty(UNDEF, types=(Legend,), dynamic=False, nullable=True) static = BoolProperty(False, dynamic=False) position = EnumProperty(POS_RIGHT, enum=POSITION_LRTB, dynamic=False) orientation = EnumProperty(ORI_VERTICAL, enum=ORIENTATION) radius = QuadProperty(3, dynamic=False) padding = QuadProperty(5, dynamic=False) spacing = NumProperty(5, dynamic=False) line = Include(LineProperties, line_color="#ddd") fill = Include(FillProperties, fill_color="#fffc") def __init__(self, **overrides): """Initializes a new instance of the OutLegend.""" # init legend glyph self._glyph = LegendBox() # init base super().__init__(**overrides) def get_extent(self, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to get amount of logical space needed to draw the object. """ # check if visible if not self.is_visible(source, overrides): return 0 # update glyph properties self._glyph.set_properties_from(self, source=source, overrides=overrides) # get bbox bbox = self._glyph.get_bbox(canvas, source, **overrides) if bbox is None: return 0 # get extent position = self.get_property('position', source, overrides) return bbox.height if position in POSITION_TB else bbox.width def prepare(self, chart, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to prepare the object. """ # check if static static = self.get_property('static', source, overrides) if static: return # clean items self.items = [] # check if visible if not self.is_visible(source, overrides): return # get items from objects items = [] for obj in chart.graphics: if isinstance(obj, InGraphics) and obj.visible: items += obj.get_legends(canvas) # set new items self.items = items def draw(self, canvas, source=UNDEF, **overrides): """Uses given canvas to draw the legend.""" # check if visible if not self.is_visible(source, overrides): return # update legend glyph self._update_glyph(canvas, source, **overrides) # draw legend self._glyph.draw(canvas) def _update_glyph(self, canvas=None, source=UNDEF, **overrides): """Updates legend glyph.""" # get properties frame = self.get_property('frame', source, overrides) position = self.get_property('position', source, overrides) # check values position = position or POS_RIGHT # get anchor if position == POS_TOP: anchor = POS_N x = frame.cx y = frame.y1 elif position == POS_RIGHT: anchor = POS_E x = frame.x2 y = frame.cy elif position == POS_BOTTOM: anchor = POS_S x = frame.cx y = frame.y2 elif position == POS_LEFT: anchor = POS_W x = frame.x1 y = frame.cy else: anchor = POS_E x = frame.x2 y = frame.cy # update glyph shared self._glyph.set_properties_from(self, source=source, overrides=overrides) # update glyph self._glyph.anchor = anchor self._glyph.x = x self._glyph.y = y class InLegend(InGraphics): """ InLegend provides a wrapper for the pero.LegendBox glyph to draw the chart legend inside the main data frame. Properties: items: (pero.Legend,), None or UNDEF Specifies a collection of legend items to draw. static: bool Specifies whether the legend items are given by user directly (True) or whether they should be retrieved automatically from parent chart (False). position: pero.POSITION_COMPASS Specifies the legend position within a chart as any item from the pero.POSITION_COMPASS enum. orientation: pero.ORIENTATION Specifies the legend orientation as any item from the pero.ORIENTATION enum. margin: int, float, (int,), (float,) or UNDEF Specifies the space around the legend box as a single value or values for individual sides starting from top. padding: int, float, (int,), (float,) or UNDEF Specifies the inner space of the legend box as a single value or values for individual sides starting from top. spacing: int or float Specifies the additional space between legend items. radius: int, float, (int,), (float,) or UNDEF Specifies the corner radius of the legend box as a single value or values for individual corners starting from top-left. line properties: Includes pero.LineProperties to specify the legend box outline. fill properties: Includes pero.FillProperties to specify the legend box fill. """ items = TupleProperty(UNDEF, types=(Legend,), dynamic=False, nullable=True) static = BoolProperty(False, dynamic=False) position = EnumProperty(POS_NE, enum=POSITION_COMPASS, dynamic=False) orientation = EnumProperty(ORI_VERTICAL, enum=ORIENTATION) margin = QuadProperty(10, dynamic=False) radius = QuadProperty(3, dynamic=False) padding = QuadProperty(5, dynamic=False) spacing = NumProperty(5, dynamic=False) line = Include(LineProperties, line_color="#ddd") fill = Include(FillProperties, fill_color="#fffc") def __init__(self, **overrides): """Initializes a new instance of the InLegend.""" # init legend glyph self._glyph = LegendBox() # init base super().__init__(**overrides) def prepare(self, chart, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to prepare the object. """ # check if static static = self.get_property('static', source, overrides) if static: return # clean items self.items = [] # check if visible if not self.is_visible(source, overrides): return # get items from objects items = [] for obj in chart.graphics: if isinstance(obj, InGraphics) and obj.visible: items += obj.get_legends(canvas) # set new items self.items = items def draw(self, canvas, source=UNDEF, **overrides): """Uses given canvas to draw the legend.""" # check if visible if not self.is_visible(source, overrides): return # update legend glyph self._update_glyph(canvas, source, **overrides) # draw legend self._glyph.draw(canvas) def _update_glyph(self, canvas=None, source=UNDEF, **overrides): """Updates legend glyph.""" # get properties frame = self.get_property('frame', source, overrides) position = self.get_property('position', source, overrides) margin = self.get_property('margin', source, overrides) # check values position = position or POS_RIGHT margin = margin or (10, 10, 10, 10) # set anchor self._glyph.anchor = position if position == POS_N: x = frame.cx y = frame.y1 + margin[0] elif position == POS_NE: x = frame.x2 - margin[1] y = frame.y1 + margin[0] elif position == POS_E: x = frame.x2 - margin[1] y = frame.cy elif position == POS_SE: x = frame.x2 - margin[1] y = frame.y2 - margin[2] elif position == POS_S: x = frame.cx y = frame.y2 - margin[2] elif position == POS_SW: x = frame.x1 + margin[3] y = frame.y2 - margin[2] elif position == POS_W: x = frame.x1 + margin[3] y = frame.cy elif position == POS_NW: x = frame.x1 + margin[3] y = frame.y1 + margin[0] elif position == POS_C: x = frame.cx y = frame.cy else: x = frame.x2 - margin[1] y = frame.y1 + margin[0] # update glyph shared self._glyph.set_properties_from(self, source=source, overrides=overrides) # update glyph self._glyph.anchor = position self._glyph.x = x self._glyph.y = y
perrot/chart/legends.py
from pero.properties import * from pero import Legend, LegendBox from .. enums import * from . graphics import InGraphics, OutGraphics class OutLegend(OutGraphics): """ OutLegend provides a wrapper for the pero.LegendBox glyph to draw the chart legend outside the main data frame. Properties: items: (pero.Legend,), None or UNDEF Specifies a collection of legend items to draw. static: bool Specifies whether the legend items are given by user directly (True) or whether they should be retrieved automatically from parent chart (False). position: pero.POSITION_LRTB Specifies the legend position within a chart as any item from the pero.POSITION_LRTB enum. orientation: pero.ORIENTATION Specifies the legend orientation as any item from the pero.ORIENTATION enum. margin: int, float, (int,), (float,) or UNDEF Specifies the space around the legend box as a single value or values for individual sides starting from top. padding: int, float, (int,), (float,) or UNDEF Specifies the inner space of the legend box as a single value or values for individual sides starting from top. spacing: int or float Specifies the additional space between legend items. radius: int, float, (int,), (float,) or UNDEF Specifies the corner radius of the legend box as a single value or values for individual corners starting from top-left. line properties: Includes pero.LineProperties to specify the legend box outline. fill properties: Includes pero.FillProperties to specify the legend box fill. """ items = TupleProperty(UNDEF, types=(Legend,), dynamic=False, nullable=True) static = BoolProperty(False, dynamic=False) position = EnumProperty(POS_RIGHT, enum=POSITION_LRTB, dynamic=False) orientation = EnumProperty(ORI_VERTICAL, enum=ORIENTATION) radius = QuadProperty(3, dynamic=False) padding = QuadProperty(5, dynamic=False) spacing = NumProperty(5, dynamic=False) line = Include(LineProperties, line_color="#ddd") fill = Include(FillProperties, fill_color="#fffc") def __init__(self, **overrides): """Initializes a new instance of the OutLegend.""" # init legend glyph self._glyph = LegendBox() # init base super().__init__(**overrides) def get_extent(self, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to get amount of logical space needed to draw the object. """ # check if visible if not self.is_visible(source, overrides): return 0 # update glyph properties self._glyph.set_properties_from(self, source=source, overrides=overrides) # get bbox bbox = self._glyph.get_bbox(canvas, source, **overrides) if bbox is None: return 0 # get extent position = self.get_property('position', source, overrides) return bbox.height if position in POSITION_TB else bbox.width def prepare(self, chart, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to prepare the object. """ # check if static static = self.get_property('static', source, overrides) if static: return # clean items self.items = [] # check if visible if not self.is_visible(source, overrides): return # get items from objects items = [] for obj in chart.graphics: if isinstance(obj, InGraphics) and obj.visible: items += obj.get_legends(canvas) # set new items self.items = items def draw(self, canvas, source=UNDEF, **overrides): """Uses given canvas to draw the legend.""" # check if visible if not self.is_visible(source, overrides): return # update legend glyph self._update_glyph(canvas, source, **overrides) # draw legend self._glyph.draw(canvas) def _update_glyph(self, canvas=None, source=UNDEF, **overrides): """Updates legend glyph.""" # get properties frame = self.get_property('frame', source, overrides) position = self.get_property('position', source, overrides) # check values position = position or POS_RIGHT # get anchor if position == POS_TOP: anchor = POS_N x = frame.cx y = frame.y1 elif position == POS_RIGHT: anchor = POS_E x = frame.x2 y = frame.cy elif position == POS_BOTTOM: anchor = POS_S x = frame.cx y = frame.y2 elif position == POS_LEFT: anchor = POS_W x = frame.x1 y = frame.cy else: anchor = POS_E x = frame.x2 y = frame.cy # update glyph shared self._glyph.set_properties_from(self, source=source, overrides=overrides) # update glyph self._glyph.anchor = anchor self._glyph.x = x self._glyph.y = y class InLegend(InGraphics): """ InLegend provides a wrapper for the pero.LegendBox glyph to draw the chart legend inside the main data frame. Properties: items: (pero.Legend,), None or UNDEF Specifies a collection of legend items to draw. static: bool Specifies whether the legend items are given by user directly (True) or whether they should be retrieved automatically from parent chart (False). position: pero.POSITION_COMPASS Specifies the legend position within a chart as any item from the pero.POSITION_COMPASS enum. orientation: pero.ORIENTATION Specifies the legend orientation as any item from the pero.ORIENTATION enum. margin: int, float, (int,), (float,) or UNDEF Specifies the space around the legend box as a single value or values for individual sides starting from top. padding: int, float, (int,), (float,) or UNDEF Specifies the inner space of the legend box as a single value or values for individual sides starting from top. spacing: int or float Specifies the additional space between legend items. radius: int, float, (int,), (float,) or UNDEF Specifies the corner radius of the legend box as a single value or values for individual corners starting from top-left. line properties: Includes pero.LineProperties to specify the legend box outline. fill properties: Includes pero.FillProperties to specify the legend box fill. """ items = TupleProperty(UNDEF, types=(Legend,), dynamic=False, nullable=True) static = BoolProperty(False, dynamic=False) position = EnumProperty(POS_NE, enum=POSITION_COMPASS, dynamic=False) orientation = EnumProperty(ORI_VERTICAL, enum=ORIENTATION) margin = QuadProperty(10, dynamic=False) radius = QuadProperty(3, dynamic=False) padding = QuadProperty(5, dynamic=False) spacing = NumProperty(5, dynamic=False) line = Include(LineProperties, line_color="#ddd") fill = Include(FillProperties, fill_color="#fffc") def __init__(self, **overrides): """Initializes a new instance of the InLegend.""" # init legend glyph self._glyph = LegendBox() # init base super().__init__(**overrides) def prepare(self, chart, canvas, source=UNDEF, **overrides): """ This method is automatically called by parent chart to prepare the object. """ # check if static static = self.get_property('static', source, overrides) if static: return # clean items self.items = [] # check if visible if not self.is_visible(source, overrides): return # get items from objects items = [] for obj in chart.graphics: if isinstance(obj, InGraphics) and obj.visible: items += obj.get_legends(canvas) # set new items self.items = items def draw(self, canvas, source=UNDEF, **overrides): """Uses given canvas to draw the legend.""" # check if visible if not self.is_visible(source, overrides): return # update legend glyph self._update_glyph(canvas, source, **overrides) # draw legend self._glyph.draw(canvas) def _update_glyph(self, canvas=None, source=UNDEF, **overrides): """Updates legend glyph.""" # get properties frame = self.get_property('frame', source, overrides) position = self.get_property('position', source, overrides) margin = self.get_property('margin', source, overrides) # check values position = position or POS_RIGHT margin = margin or (10, 10, 10, 10) # set anchor self._glyph.anchor = position if position == POS_N: x = frame.cx y = frame.y1 + margin[0] elif position == POS_NE: x = frame.x2 - margin[1] y = frame.y1 + margin[0] elif position == POS_E: x = frame.x2 - margin[1] y = frame.cy elif position == POS_SE: x = frame.x2 - margin[1] y = frame.y2 - margin[2] elif position == POS_S: x = frame.cx y = frame.y2 - margin[2] elif position == POS_SW: x = frame.x1 + margin[3] y = frame.y2 - margin[2] elif position == POS_W: x = frame.x1 + margin[3] y = frame.cy elif position == POS_NW: x = frame.x1 + margin[3] y = frame.y1 + margin[0] elif position == POS_C: x = frame.cx y = frame.cy else: x = frame.x2 - margin[1] y = frame.y1 + margin[0] # update glyph shared self._glyph.set_properties_from(self, source=source, overrides=overrides) # update glyph self._glyph.anchor = position self._glyph.x = x self._glyph.y = y
0.910376
0.572006
from typing import Optional from pydantic import BaseModel, EmailStr, Field from enum import Enum from typing import List class Gender(str, Enum): # Gender에 들어갈수있는 종류 4개 미리 선언 male = 'male' female = 'female' other = 'other' not_given = 'not_given' class UserSchema(BaseModel): # 앱으로부터 받은 유저데이터가 MongoDB에 저장할것인지 알려주는 스키마 # ...은 이 필드가 필수임을 나타낸다. None으로 바꿔도 무방 userid: str = Field(...) fullname: str = Field(...) email: EmailStr = Field(...) gender: Gender = Field(...) age: int = Field(...,gt=0,lt=100) # gt(greater than)와 lt(less than)는 값이 1~9까지 세팅. 즉, 0, 10, 11 값은 에러 송출 height: int = Field(...) weight: int = Field(...) class UserBCM(BaseModel): # 앱으로부터 받은 MDCW의 측정데이터가 MongoDB에 저장할것인지 알려주는 스키마 userid: str = Field(...) # 매치시킬것은 ID로 하자 bcmdata: str = Field(...) # bcm은 T를 제외한 값들 64byte인가를 받자. gainPD1: float = Field(...) gainPD2: float = Field(...) gainPD3: float = Field(...) class Config: # 입력되는 데이터가 어떠한 형식으로 되야하는지에 대한 예시 schema_extra = { "example": { "userid": "gwangjin", "bcmdata": "T00DF039600F4h399F087B0C6Bh2310058E0730h2530072909C9h083D01EE0005h1E6F0106000D\nT1DBE07380B09h274808060B9Bh2341056F060Fh2493071909B7h0894021B03B1h1E9700F10089\nT1DC207610A0Fh271407FC0C00h22BF059F0673h247D06F90A28h0842020A0386h1E8500E10186\nT1DC407980B47h265907DA0BFDh229A054D0741h2518073009E9h08AC02240142h1E7B00D800E4\nT1DC407B60BB6h25E208130AE0h21EB055C05B9h249B06B80AA1h098603200119h1F8300FA0021\nT1DCB07710B04h272B07F60C15h232405AC06DFh23EA06FB0B0Fh096502640433h1ED201090180\nT1DCC07500BA6h2789081A0BCBh22B305490779h250907650AAEh08BC02990322h1ECA00E400FF\nT1DC1076C0B72h272708120AA7h22AC05BC06B6h249407070A6Eh08FE02120084h1F25010F0195\nT1DC507150AA3h273D08480AD9h21CC057D0742h248706B50AA2h09C0035101B7h1F6800F0017B\n", "gainPD1": 10.832, "gainPD2": 94.15, "gainPD3": 119.391 } } class UserPhysio(BaseModel): # 서버내에서 인공지능으로 예측한 결과 분석데이터가 MongoDB에 저장할것인지 알려주는 스키마 time: List[float] = Field(...) mua685: List[float] = Field(...) mua785: List[float] = Field(...) mua830: List[float] = Field(...) mua850: List[float] = Field(...) mua915: List[float] = Field(...) mua975: List[float] = Field(...) mus685: List[float] = Field(...) mus785: List[float] = Field(...) mus830: List[float] = Field(...) mus850: List[float] = Field(...) mus915: List[float] = Field(...) mus975: List[float] = Field(...) hbo2: List[float] = Field(...) hhb: List[float] = Field(...) fat: List[float] = Field(...) water: List[float] = Field(...) class Config: # 입력되는 데이터가 어떠한 형식으로 되야하는지에 대한 예시 schema_extra = { "example": { "userid": "gwangjin", "time":[1,2], "mua685": [8.42641683, 1.22293563], "mua785": [7.08869255, 1.62395152], "mua830": [7.43068556, 1.67743087], "mua850": [6.29488418 ,0.93608081], "mua915": [6.90653301, 1.6422445 ], "mua975": [6.90653301, 1.6422445 ], "mus685": [6.90653301, 1.6422445 ], "mus785": [6.90653301, 1.6422445 ], "mus830": [6.90653301, 1.6422445 ], "mus850": [6.90653301, 1.6422445 ], "mus915": [6.90653301, 1.6422445 ], "mus975": [6.90653301, 1.6422445 ], "hbo2": [6.90653301, 1.6422445 ], "hhb": [6.90653301, 1.6422445 ], "fat": [6.90653301 ,1.6422445 ], "water": [6.90653301 ,1.6422445 ], } } class UserIn(UserSchema): # 앱으로부터 받은 유저데이터가 서버내에서 어떻게 처리될지 알려주는 스키마 여기서는 password 필드를 추가해서 보여준다. password: str = Field(...) class Config: schema_extra = { "example": { "userid": "abc123", "password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 24, "height": 171, "weight": 75, } } class UserOut(UserSchema): pass class UserInDB(UserSchema): # 앱으로부터 받은 유저데이터가 MongoDB에 저장될때는 hash함수로 암호화되어 hase_password로 저장시킨다. hashed_password: str class Config: schema_extra = { "example": { "userid": "abc123", "hashed_password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 24, "height": 171, "weight": 75, } } class UpdateUserModel(BaseModel): # 앱으로부터 유저데이터 수정을 요청했을때 받는 서버에서 받을 수 있는 형식 userid: Optional[str] password: Optional[str] fullname: Optional[str] email: Optional[EmailStr] gender: Optional[str] birth: Optional[int] height: Optional[int] weitht: Optional[int] class Config: schema_extra = { "example": { "userid": "dcf123", "password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 25, "height": 172, "weight": 75, } } def ResponseModel(data, message): # 앱에서 호출한 결과를 반환해주는 함수 성공적으로 했을때, 아래와 같다. return { "data": [data], "code": 200, "message": message, } def ResponseModelForBCM(data, message): # 앱에서 호출한 결과를 반환해주는 함수 성공적으로 했을때, 아래와 같다. return { "data": data, "code": 200, "message": message, } def ErrorResponseModel(error, code, message): # 앱에서 호출한 결과를 반환해주는 함수 실패로 되었을때, 아래와 같다. return {"error": error, "code": code, "message": message}
app/server/models/user.py
from typing import Optional from pydantic import BaseModel, EmailStr, Field from enum import Enum from typing import List class Gender(str, Enum): # Gender에 들어갈수있는 종류 4개 미리 선언 male = 'male' female = 'female' other = 'other' not_given = 'not_given' class UserSchema(BaseModel): # 앱으로부터 받은 유저데이터가 MongoDB에 저장할것인지 알려주는 스키마 # ...은 이 필드가 필수임을 나타낸다. None으로 바꿔도 무방 userid: str = Field(...) fullname: str = Field(...) email: EmailStr = Field(...) gender: Gender = Field(...) age: int = Field(...,gt=0,lt=100) # gt(greater than)와 lt(less than)는 값이 1~9까지 세팅. 즉, 0, 10, 11 값은 에러 송출 height: int = Field(...) weight: int = Field(...) class UserBCM(BaseModel): # 앱으로부터 받은 MDCW의 측정데이터가 MongoDB에 저장할것인지 알려주는 스키마 userid: str = Field(...) # 매치시킬것은 ID로 하자 bcmdata: str = Field(...) # bcm은 T를 제외한 값들 64byte인가를 받자. gainPD1: float = Field(...) gainPD2: float = Field(...) gainPD3: float = Field(...) class Config: # 입력되는 데이터가 어떠한 형식으로 되야하는지에 대한 예시 schema_extra = { "example": { "userid": "gwangjin", "bcmdata": "T00DF039600F4h399F087B0C6Bh2310058E0730h2530072909C9h083D01EE0005h1E6F0106000D\nT1DBE07380B09h274808060B9Bh2341056F060Fh2493071909B7h0894021B03B1h1E9700F10089\nT1DC207610A0Fh271407FC0C00h22BF059F0673h247D06F90A28h0842020A0386h1E8500E10186\nT1DC407980B47h265907DA0BFDh229A054D0741h2518073009E9h08AC02240142h1E7B00D800E4\nT1DC407B60BB6h25E208130AE0h21EB055C05B9h249B06B80AA1h098603200119h1F8300FA0021\nT1DCB07710B04h272B07F60C15h232405AC06DFh23EA06FB0B0Fh096502640433h1ED201090180\nT1DCC07500BA6h2789081A0BCBh22B305490779h250907650AAEh08BC02990322h1ECA00E400FF\nT1DC1076C0B72h272708120AA7h22AC05BC06B6h249407070A6Eh08FE02120084h1F25010F0195\nT1DC507150AA3h273D08480AD9h21CC057D0742h248706B50AA2h09C0035101B7h1F6800F0017B\n", "gainPD1": 10.832, "gainPD2": 94.15, "gainPD3": 119.391 } } class UserPhysio(BaseModel): # 서버내에서 인공지능으로 예측한 결과 분석데이터가 MongoDB에 저장할것인지 알려주는 스키마 time: List[float] = Field(...) mua685: List[float] = Field(...) mua785: List[float] = Field(...) mua830: List[float] = Field(...) mua850: List[float] = Field(...) mua915: List[float] = Field(...) mua975: List[float] = Field(...) mus685: List[float] = Field(...) mus785: List[float] = Field(...) mus830: List[float] = Field(...) mus850: List[float] = Field(...) mus915: List[float] = Field(...) mus975: List[float] = Field(...) hbo2: List[float] = Field(...) hhb: List[float] = Field(...) fat: List[float] = Field(...) water: List[float] = Field(...) class Config: # 입력되는 데이터가 어떠한 형식으로 되야하는지에 대한 예시 schema_extra = { "example": { "userid": "gwangjin", "time":[1,2], "mua685": [8.42641683, 1.22293563], "mua785": [7.08869255, 1.62395152], "mua830": [7.43068556, 1.67743087], "mua850": [6.29488418 ,0.93608081], "mua915": [6.90653301, 1.6422445 ], "mua975": [6.90653301, 1.6422445 ], "mus685": [6.90653301, 1.6422445 ], "mus785": [6.90653301, 1.6422445 ], "mus830": [6.90653301, 1.6422445 ], "mus850": [6.90653301, 1.6422445 ], "mus915": [6.90653301, 1.6422445 ], "mus975": [6.90653301, 1.6422445 ], "hbo2": [6.90653301, 1.6422445 ], "hhb": [6.90653301, 1.6422445 ], "fat": [6.90653301 ,1.6422445 ], "water": [6.90653301 ,1.6422445 ], } } class UserIn(UserSchema): # 앱으로부터 받은 유저데이터가 서버내에서 어떻게 처리될지 알려주는 스키마 여기서는 password 필드를 추가해서 보여준다. password: str = Field(...) class Config: schema_extra = { "example": { "userid": "abc123", "password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 24, "height": 171, "weight": 75, } } class UserOut(UserSchema): pass class UserInDB(UserSchema): # 앱으로부터 받은 유저데이터가 MongoDB에 저장될때는 hash함수로 암호화되어 hase_password로 저장시킨다. hashed_password: str class Config: schema_extra = { "example": { "userid": "abc123", "hashed_password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 24, "height": 171, "weight": 75, } } class UpdateUserModel(BaseModel): # 앱으로부터 유저데이터 수정을 요청했을때 받는 서버에서 받을 수 있는 형식 userid: Optional[str] password: Optional[str] fullname: Optional[str] email: Optional[EmailStr] gender: Optional[str] birth: Optional[int] height: Optional[int] weitht: Optional[int] class Config: schema_extra = { "example": { "userid": "dcf123", "password": "<PASSWORD>", "fullname": "<NAME>", "email": "<EMAIL>", "gender": "male", "age": 25, "height": 172, "weight": 75, } } def ResponseModel(data, message): # 앱에서 호출한 결과를 반환해주는 함수 성공적으로 했을때, 아래와 같다. return { "data": [data], "code": 200, "message": message, } def ResponseModelForBCM(data, message): # 앱에서 호출한 결과를 반환해주는 함수 성공적으로 했을때, 아래와 같다. return { "data": data, "code": 200, "message": message, } def ErrorResponseModel(error, code, message): # 앱에서 호출한 결과를 반환해주는 함수 실패로 되었을때, 아래와 같다. return {"error": error, "code": code, "message": message}
0.549882
0.517998
import boto3 import click import json from operator import itemgetter from sys import exit @click.command() @click.option('-r', '--region', help='AWS region to use') @click.option('-z', '--availability-zone', multiple=True, help="Availability Zones to use, use 'all' for all zones, multiple invocations supported, default all", default=["all"]) @click.option('-t', '--instance-type', multiple=True, help="Instance types to use, multiple invocations supported, default t3.micro", default=["t3.micro"]) @click.option('--cheapest/--all', default=False) @click.option('-p', '--profile', help="AWS profile to use") @click.option('-f', '--format', type=click.Choice(['json', 'text']), help="output format", default='text') def cli(region, availability_zone, instance_type, format, profile, cheapest): if profile is not None: session = boto3.Session(profile_name=profile) else: session = boto3.Session() if region is not None: ec2 = session.client("ec2", region_name=region) else: ec2 = session.client("ec2") az_query = ec2.describe_availability_zones() az_available = [] for zone in az_query['AvailabilityZones']: az_available.append(zone['ZoneName']) if "all" in availability_zone: azs = az_available else: azs = [] for zone in availability_zone: zone_name = zone if len(zone) == 1: zone_name = "{}{}".format(region, zone) if zone_name not in az_available: print("Zone not available: {}, available zones: ".format(zone_name, az_available)) exit(1) else: azs.append(zone_name) results = [] instance_types = instance_type # less ambiguous for zone in azs: for instance_type in instance_types: # get last price last = ec2.describe_spot_price_history(InstanceTypes=[instance_type], MaxResults=1, ProductDescriptions=['Linux/UNIX (Amazon VPC)'], AvailabilityZone=zone) if len(last['SpotPriceHistory']) == 0: print("warning, no spot price history for instance type: {}, AZ: {}. Instance type may not" "be availablein this region.".format(instance_type, zone)) else: results.append({'az': zone, 'type': instance_type, 'price': float(last['SpotPriceHistory'][-1]['SpotPrice'])}) if len(results) == 0: print("No results, invalid instance types?") exit(1) if cheapest: output = [sorted(results, key=itemgetter('price'))[0]] else: output = sorted(results, key=itemgetter('price')) if format == "json": print(json.dumps(output)) elif format == "text": print("AZ\t\tInstance Type\tSpot Price") for line in output: print("{}\t{}\t{}".format(line['az'], line['type'], line['price']))
spottpreis.py
import boto3 import click import json from operator import itemgetter from sys import exit @click.command() @click.option('-r', '--region', help='AWS region to use') @click.option('-z', '--availability-zone', multiple=True, help="Availability Zones to use, use 'all' for all zones, multiple invocations supported, default all", default=["all"]) @click.option('-t', '--instance-type', multiple=True, help="Instance types to use, multiple invocations supported, default t3.micro", default=["t3.micro"]) @click.option('--cheapest/--all', default=False) @click.option('-p', '--profile', help="AWS profile to use") @click.option('-f', '--format', type=click.Choice(['json', 'text']), help="output format", default='text') def cli(region, availability_zone, instance_type, format, profile, cheapest): if profile is not None: session = boto3.Session(profile_name=profile) else: session = boto3.Session() if region is not None: ec2 = session.client("ec2", region_name=region) else: ec2 = session.client("ec2") az_query = ec2.describe_availability_zones() az_available = [] for zone in az_query['AvailabilityZones']: az_available.append(zone['ZoneName']) if "all" in availability_zone: azs = az_available else: azs = [] for zone in availability_zone: zone_name = zone if len(zone) == 1: zone_name = "{}{}".format(region, zone) if zone_name not in az_available: print("Zone not available: {}, available zones: ".format(zone_name, az_available)) exit(1) else: azs.append(zone_name) results = [] instance_types = instance_type # less ambiguous for zone in azs: for instance_type in instance_types: # get last price last = ec2.describe_spot_price_history(InstanceTypes=[instance_type], MaxResults=1, ProductDescriptions=['Linux/UNIX (Amazon VPC)'], AvailabilityZone=zone) if len(last['SpotPriceHistory']) == 0: print("warning, no spot price history for instance type: {}, AZ: {}. Instance type may not" "be availablein this region.".format(instance_type, zone)) else: results.append({'az': zone, 'type': instance_type, 'price': float(last['SpotPriceHistory'][-1]['SpotPrice'])}) if len(results) == 0: print("No results, invalid instance types?") exit(1) if cheapest: output = [sorted(results, key=itemgetter('price'))[0]] else: output = sorted(results, key=itemgetter('price')) if format == "json": print(json.dumps(output)) elif format == "text": print("AZ\t\tInstance Type\tSpot Price") for line in output: print("{}\t{}\t{}".format(line['az'], line['type'], line['price']))
0.131898
0.094845
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. """Parsers for the language implementation.""" ALTERNATE = CONCAT = EXP = PROCESS = None class Parser: """Generic parser from which all parsers must inherit.""" def __repr__(self): return self.repr() def __add__(self, other): global CONCAT if CONCAT is None: from scripting.parser.combinator import Concat as CONCAT return CONCAT(self, other) def __mul__(self, other): global EXP if EXP is None: from scripting.parser.combinator import Exp as EXP return EXP(self, other) def __or__(self, other): global ALTERNATE if ALTERNATE is None: from scripting.parser.combinator import Alternate as ALTERNATE return ALTERNATE(self, other) def __xor__(self, function): global PROCESS if PROCESS is None: from scripting.parser.combinator import Process as PROCESS return PROCESS(self, function) # Display methods def repr(self, seen=None): """Display the given parsers.""" return type(self).__name__ def repr_several(self, connector, *parsers, seen=None): """Represent several parsers.""" seen = seen or [] results = [] for parser in parsers: if parser in seen: results.append(f"{type(parser).__name__}(...)") else: results.append(f"{parser.repr(seen)}") return connector.join(results)
src/scripting/parser/parser.py
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. """Parsers for the language implementation.""" ALTERNATE = CONCAT = EXP = PROCESS = None class Parser: """Generic parser from which all parsers must inherit.""" def __repr__(self): return self.repr() def __add__(self, other): global CONCAT if CONCAT is None: from scripting.parser.combinator import Concat as CONCAT return CONCAT(self, other) def __mul__(self, other): global EXP if EXP is None: from scripting.parser.combinator import Exp as EXP return EXP(self, other) def __or__(self, other): global ALTERNATE if ALTERNATE is None: from scripting.parser.combinator import Alternate as ALTERNATE return ALTERNATE(self, other) def __xor__(self, function): global PROCESS if PROCESS is None: from scripting.parser.combinator import Process as PROCESS return PROCESS(self, function) # Display methods def repr(self, seen=None): """Display the given parsers.""" return type(self).__name__ def repr_several(self, connector, *parsers, seen=None): """Represent several parsers.""" seen = seen or [] results = [] for parser in parsers: if parser in seen: results.append(f"{type(parser).__name__}(...)") else: results.append(f"{parser.repr(seen)}") return connector.join(results)
0.680666
0.055643
from ..DB.Repositorio_Grado_De_Ocupacion_Por_Plazas_INE import RepositoryGradoOcupacionPlazasINE as DBRepository from ..Utilidades.Conversores import Conversores as Conversor def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio(Ciudad, Anio): """ Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año :param Ciudad: Ciudad :type Ciudad: str :param Anio: Anio :type Anio: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnAnio(Ciudad, Anio) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio_mensualmente(Ciudad, Anio): """ Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año dividido por meses Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año dividido por meses :param Ciudad: Ciudad :type Ciudad: str :param Anio: Anio :type Anio: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnAnioMensualmente(Ciudad, Anio) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios(Ciudad, AnioInicio, AnioFin): """ Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAnios(Ciudad, AnioInicio, AnioFin) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios_mensualmente(Ciudad, AnioInicio, AnioFin): """ Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años mensualmente Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años mensualmente :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAnios(Ciudad, AnioInicio, AnioFin) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios_en_mes(Ciudad, AnioInicio, AnioFin, Mes): """ Dado una ciudad, un mes y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años en ese mes Dado una ciudad, un mes y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años en ese mes :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :param Mes: Mes :type Mes: str :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAniosEnMes(Ciudad, AnioInicio, AnioFin, Mes) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval
controllers/grado de ocupacion por plazas ine_controller.py
from ..DB.Repositorio_Grado_De_Ocupacion_Por_Plazas_INE import RepositoryGradoOcupacionPlazasINE as DBRepository from ..Utilidades.Conversores import Conversores as Conversor def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio(Ciudad, Anio): """ Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año :param Ciudad: Ciudad :type Ciudad: str :param Anio: Anio :type Anio: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnAnio(Ciudad, Anio) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio_mensualmente(Ciudad, Anio): """ Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año dividido por meses Dado una ciudad y un año obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en ese año dividido por meses :param Ciudad: Ciudad :type Ciudad: str :param Anio: Anio :type Anio: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnAnioMensualmente(Ciudad, Anio) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios(Ciudad, AnioInicio, AnioFin): """ Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAnios(Ciudad, AnioInicio, AnioFin) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios_mensualmente(Ciudad, AnioInicio, AnioFin): """ Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años mensualmente Dado una ciudad y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años mensualmente :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAnios(Ciudad, AnioInicio, AnioFin) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_rango_anios_en_mes(Ciudad, AnioInicio, AnioFin, Mes): """ Dado una ciudad, un mes y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años en ese mes Dado una ciudad, un mes y un rango de años obtiene el grado de ocupacion por tanto por cien por plazas en dicha ciudad en esos años en ese mes :param Ciudad: Ciudad :type Ciudad: str :param AnioInicio: Anio Inicio :type AnioInicio: int :param AnioFin: Anio Fin :type AnioFin: int :param Mes: Mes :type Mes: str :rtype: None """ conversor = Conversor() repository = DBRepository() cursor, labels = repository.ObtenerPorcentajeDelGradoDeOcupacionPorPlazasEnCiudadEnRangoAniosEnMes(Ciudad, AnioInicio, AnioFin, Mes) arrayTuplas = conversor.ConvertirCursorToTuplas(cursor) ##Mostrar JSON Extendido matriz, lista = conversor.ConvertirTuplasToMatriz(arrayTuplas, labels) retval = conversor.ObtenerDataJSONExtendido(matriz) return retval
0.398992
0.577495
from __future__ import unicode_literals from django.http import Http404 from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rolepermissions.exceptions import RoleDoesNotExist from rolepermissions.roles import RolesManager def get_permission(permission_name): user_ct = ContentType.objects.get_for_model(get_user_model()) permission, created = Permission.objects.get_or_create(content_type=user_ct, codename=permission_name) return permission def get_user_role(user): if user: roles = user.groups.filter(name__in=RolesManager.get_roles_names()) if roles: return RolesManager.retrieve_role(roles[0].name) return None def available_perm_status(user): role = get_user_role(user) permissions = UserPermission.objects.filter(user=user) permissions = { p.permission_name: p for p in permissions } user_permissions = [] if role: for permission_name in role.permission_names_list(): if permission_name in permissions: permission = permissions[permission_name] else: permission = UserPermission(user=user, permission_name=permission_name, is_granted=role.get_default(permission_name)) permission.save() user_permissions.append(permission) permission_hash = { p.permission_name: p.is_granted for p in user_permissions } return permission_hash def grant_permission(user, permission_name): role = get_user_role(user) if role and permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.add(permission) return True return False def revoke_permission(user, permission_name): role = get_user_role(user) if role and permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.remove(permission) return True return False def retrieve_role(role_name): return RolesManager.retrieve_role(role_name)
rolepermissions/shortcuts.py
from __future__ import unicode_literals from django.http import Http404 from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rolepermissions.exceptions import RoleDoesNotExist from rolepermissions.roles import RolesManager def get_permission(permission_name): user_ct = ContentType.objects.get_for_model(get_user_model()) permission, created = Permission.objects.get_or_create(content_type=user_ct, codename=permission_name) return permission def get_user_role(user): if user: roles = user.groups.filter(name__in=RolesManager.get_roles_names()) if roles: return RolesManager.retrieve_role(roles[0].name) return None def available_perm_status(user): role = get_user_role(user) permissions = UserPermission.objects.filter(user=user) permissions = { p.permission_name: p for p in permissions } user_permissions = [] if role: for permission_name in role.permission_names_list(): if permission_name in permissions: permission = permissions[permission_name] else: permission = UserPermission(user=user, permission_name=permission_name, is_granted=role.get_default(permission_name)) permission.save() user_permissions.append(permission) permission_hash = { p.permission_name: p.is_granted for p in user_permissions } return permission_hash def grant_permission(user, permission_name): role = get_user_role(user) if role and permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.add(permission) return True return False def revoke_permission(user, permission_name): role = get_user_role(user) if role and permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.remove(permission) return True return False def retrieve_role(role_name): return RolesManager.retrieve_role(role_name)
0.444565
0.092237
from __future__ import absolute_import, division, print_function import operator import bisect from . import DDesc, Capabilities def cat_descriptor_iter(ddlist): for i, dd in enumerate(ddlist): for el in dd: yield el class Cat_DDesc(DDesc): """ A Blaze data descriptor which concatenates a list of data descriptors, all of which have the same dshape after the first dimension. This presently doesn't support leading dimensions whose size is unknown (i.e. streaming dimensions). """ def __init__(self, ddlist): if len(ddlist) <= 1: raise ValueError('Need at least 2 data descriptors to concatenate') for dd in ddlist: if not isinstance(dd, DDesc): raise ValueError('Provided ddlist has an element ' 'which is not a data descriptor') self._ddlist = ddlist self._dshape = ds.cat_dshapes([dd.dshape for dd in ddlist]) self._ndim = len(self._dshape[:]) - 1 # Create a list of boundary indices boundary_index = [0] for dd in ddlist: dim_size = operator.index(dd.dshape[0]) boundary_index.append(dim_size + boundary_index[-1]) self._boundary_index = boundary_index @property def dshape(self): return self._dshape @property def capabilities(self): """The capabilities for the cat data descriptor.""" return Capabilities( immutable = True, deferred = True, # persistency is not supported yet persistent = False, appendable = False, remote = False, ) def __len__(self): return self._boundary_index[-1] def __getitem__(self, key): if not isinstance(key, tuple): key = (key,) # Just integer indices (no slices) for now boundary_index = self._boundary_index dim_size = boundary_index[-1] # TODO: Handle a slice in key[0] too! idx0 = operator.index(key[0]) # Determine which data descriptor in the list to use if idx0 >= 0: if idx0 >= dim_size: raise IndexError(('Index %d is out of range ' 'in dimension sized %d') % (idx0, dim_size)) else: if idx0 < -dim_size: raise IndexError(('Index %d is out of range ' 'in dimension sized %d') % (idx0, dim_size)) idx0 += dim_size i = bisect.bisect_right(boundary_index, idx0) - 1 # Call the i-th data descriptor to get the result return self._ddlist[i][(idx0 - boundary_index[i],) + key[1:]] def __iter__(self): return cat_descriptor_iter(self._ddlist)
blaze/datadescriptor/cat_data_descriptor.py
from __future__ import absolute_import, division, print_function import operator import bisect from . import DDesc, Capabilities def cat_descriptor_iter(ddlist): for i, dd in enumerate(ddlist): for el in dd: yield el class Cat_DDesc(DDesc): """ A Blaze data descriptor which concatenates a list of data descriptors, all of which have the same dshape after the first dimension. This presently doesn't support leading dimensions whose size is unknown (i.e. streaming dimensions). """ def __init__(self, ddlist): if len(ddlist) <= 1: raise ValueError('Need at least 2 data descriptors to concatenate') for dd in ddlist: if not isinstance(dd, DDesc): raise ValueError('Provided ddlist has an element ' 'which is not a data descriptor') self._ddlist = ddlist self._dshape = ds.cat_dshapes([dd.dshape for dd in ddlist]) self._ndim = len(self._dshape[:]) - 1 # Create a list of boundary indices boundary_index = [0] for dd in ddlist: dim_size = operator.index(dd.dshape[0]) boundary_index.append(dim_size + boundary_index[-1]) self._boundary_index = boundary_index @property def dshape(self): return self._dshape @property def capabilities(self): """The capabilities for the cat data descriptor.""" return Capabilities( immutable = True, deferred = True, # persistency is not supported yet persistent = False, appendable = False, remote = False, ) def __len__(self): return self._boundary_index[-1] def __getitem__(self, key): if not isinstance(key, tuple): key = (key,) # Just integer indices (no slices) for now boundary_index = self._boundary_index dim_size = boundary_index[-1] # TODO: Handle a slice in key[0] too! idx0 = operator.index(key[0]) # Determine which data descriptor in the list to use if idx0 >= 0: if idx0 >= dim_size: raise IndexError(('Index %d is out of range ' 'in dimension sized %d') % (idx0, dim_size)) else: if idx0 < -dim_size: raise IndexError(('Index %d is out of range ' 'in dimension sized %d') % (idx0, dim_size)) idx0 += dim_size i = bisect.bisect_right(boundary_index, idx0) - 1 # Call the i-th data descriptor to get the result return self._ddlist[i][(idx0 - boundary_index[i],) + key[1:]] def __iter__(self): return cat_descriptor_iter(self._ddlist)
0.637031
0.313433
from typing import List, Optional, Union import numpy as np import pandas as pd import pytest import scipy.sparse as sps import tabmat as tm from tabmat import from_pandas from tabmat.constructor import _split_sparse_and_dense_parts from tabmat.dense_matrix import DenseMatrix from tabmat.ext.sparse import csr_dense_sandwich from tabmat.split_matrix import SplitMatrix N = 100 def make_X() -> np.ndarray: X = np.zeros((N, 4)) X[:, 0] = 1.0 X[:10, 1] = 0.5 X[-20:, 2] = 0.25 X[:, 3] = 2.0 return X @pytest.fixture def X() -> np.ndarray: return make_X() def test_csc_to_split(X: np.ndarray): for T, D, S in [(0.05, 4, 0), (0.1, 3, 1), (0.2, 2, 2), (0.3, 2, 2), (1.0, 0, 4)]: dense, sparse, dense_ix, sparse_ix = _split_sparse_and_dense_parts( sps.csc_matrix(X), T ) fully_dense = SplitMatrix([dense, sparse], [dense_ix, sparse_ix]) if S == 0: assert fully_dense.indices[0].shape[0] == D assert len(fully_dense.indices) == 1 elif D == 0: assert fully_dense.indices[0].shape[0] == S assert len(fully_dense.indices) == 1 else: assert fully_dense.indices[0].shape[0] == D assert fully_dense.indices[1].shape[0] == S def split_mat() -> SplitMatrix: X = make_X() threshold = 0.1 cat_mat = tm.CategoricalMatrix(np.random.choice(range(4), X.shape[0])) dense, sparse, dense_ix, sparse_ix = _split_sparse_and_dense_parts( sps.csc_matrix(X), threshold ) cat_start = 1 + max(dense_ix.max(), sparse_ix.max()) mat = SplitMatrix( [dense, sparse, cat_mat], [dense_ix, sparse_ix, range(cat_start, cat_start + cat_mat.shape[1])], ) return mat def get_split_with_cat_components() -> List[ Union[tm.SparseMatrix, tm.DenseMatrix, tm.CategoricalMatrix] ]: n_rows = 10 np.random.seed(0) dense_1 = tm.DenseMatrix(np.random.random((n_rows, 3))) sparse_1 = tm.SparseMatrix(sps.random(n_rows, 3).tocsc()) cat = tm.CategoricalMatrix(np.random.choice(range(3), n_rows)) dense_2 = tm.DenseMatrix(np.random.random((n_rows, 3))) sparse_2 = tm.SparseMatrix(sps.random(n_rows, 3, density=0.5).tocsc()) cat_2 = tm.CategoricalMatrix(np.random.choice(range(3), n_rows), drop_first=True) return [dense_1, sparse_1, cat, dense_2, sparse_2, cat_2] def split_with_cat() -> SplitMatrix: """Initialized with multiple sparse and dense parts and no indices.""" return tm.SplitMatrix(get_split_with_cat_components()) def split_with_cat_64() -> SplitMatrix: mat = tm.SplitMatrix(get_split_with_cat_components()) matrices = mat.matrices for i, mat_ in enumerate(mat.matrices): if isinstance(mat_, tm.SparseMatrix): matrices[i] = tm.SparseMatrix( ( mat_.data, mat_.indices.astype(np.int64), mat_.indptr.astype(np.int64), ), shape=mat_.shape, ) elif isinstance(mat_, tm.DenseMatrix): matrices[i] = mat_.astype(np.float64) return tm.SplitMatrix(matrices, mat.indices) @pytest.mark.parametrize("mat", [split_with_cat(), split_with_cat_64()]) def test_init(mat: SplitMatrix): assert len(mat.indices) == 4 assert len(mat.matrices) == 4 assert (mat.indices[0] == np.concatenate([np.arange(3), np.arange(9, 12)])).all() assert mat.matrices[0].shape == (10, 6) assert mat.matrices[1].shape == (10, 6) assert mat.matrices[2].shape == (10, 3) def test_init_unsorted_indices(): dense = tm.DenseMatrix(np.random.random((10, 3))) with pytest.raises(ValueError): tm.SplitMatrix([dense], [[1, 0, 2]]) @pytest.mark.parametrize( "Acols", [np.arange(2, dtype=np.int32), np.array([1], dtype=np.int32)] ) @pytest.mark.parametrize( "Bcols", [ np.arange(4, dtype=np.int32), np.array([1], dtype=np.int32), np.array([1, 3], dtype=np.int32), ], ) def test_sandwich_sparse_dense(X: np.ndarray, Acols, Bcols): np.random.seed(0) n, k = X.shape d = np.random.random((n,)) A = sps.random(n, 2).tocsr() rows = np.arange(d.shape[0], dtype=np.int32) result = csr_dense_sandwich(A, X, d, rows, Acols, Bcols) expected = A.T.A[Acols, :] @ np.diag(d) @ X[:, Bcols] np.testing.assert_allclose(result, expected) # TODO: ensure cols are in order @pytest.mark.parametrize("mat", [split_mat(), split_with_cat(), split_with_cat_64()]) @pytest.mark.parametrize( "cols", [None, [0], [1, 2, 3], [1, 5]], ) def test_sandwich(mat: tm.SplitMatrix, cols): for _ in range(10): v = np.random.rand(mat.shape[0]) y1 = mat.sandwich(v, cols=cols) mat_limited = mat.A if cols is None else mat.A[:, cols] y2 = (mat_limited.T * v[None, :]) @ mat_limited np.testing.assert_allclose(y1, y2, atol=1e-12) @pytest.mark.parametrize("mat", [split_mat(), split_with_cat(), split_with_cat_64()]) @pytest.mark.parametrize("cols", [None, [0], [1, 2, 3], [1, 5]]) def test_split_col_subsets(mat: tm.SplitMatrix, cols): subset_cols_indices, subset_cols, n_cols = mat._split_col_subsets(cols) n_cols_correct = mat.shape[1] if cols is None else len(cols) def _get_lengths(vec_list: List[Optional[np.ndarray]]): return ( mat_.shape[1] if v is None else len(v) for v, mat_ in zip(vec_list, mat.matrices) ) assert n_cols == n_cols_correct assert sum(_get_lengths(subset_cols_indices)) == n_cols assert sum(_get_lengths(subset_cols)) == n_cols if cols is not None: cols = np.asarray(cols) for i in range(len(mat.indices)): if cols is not None: assert ( mat.indices[i][subset_cols[i]] == cols[subset_cols_indices[i]] ).all() else: assert subset_cols[i] is None assert (mat.indices[i] == subset_cols_indices[i]).all() def random_split_matrix(seed=0, n_rows=10, n_cols_per=3): if seed is not None: np.random.seed(seed) dense_1 = tm.DenseMatrix(np.random.random((n_rows, n_cols_per))) sparse = tm.SparseMatrix(sps.random(n_rows, n_cols_per).tocsc()) cat = tm.CategoricalMatrix(np.random.choice(range(n_cols_per), n_rows)) dense_2 = tm.DenseMatrix(np.random.random((n_rows, n_cols_per))) cat_2 = tm.CategoricalMatrix(np.random.choice(range(n_cols_per), n_rows)) mat = tm.SplitMatrix([dense_1, sparse, cat, dense_2, cat_2]) return mat def many_random_tests(checker): for i in range(10): mat = random_split_matrix( seed=(1 if i == 0 else None), n_rows=np.random.randint(130), n_cols_per=1 + np.random.randint(10), ) checker(mat) def test_sandwich_many_types(): def check(mat): d = np.random.random(mat.shape[0]) res = mat.sandwich(d) expected = (mat.A.T * d[None, :]) @ mat.A np.testing.assert_allclose(res, expected) many_random_tests(check) def test_transpose_matvec_many_types(): def check(mat): d = np.random.random(mat.shape[0]) res = mat.transpose_matvec(d) expected = mat.A.T.dot(d) np.testing.assert_almost_equal(res, expected) many_random_tests(check) def test_matvec_many_types(): def check(mat): d = np.random.random(mat.shape[1]) res = mat.matvec(d) expected = mat.A.dot(d) np.testing.assert_almost_equal(res, expected) many_random_tests(check) def test_init_from_1d(): m1 = DenseMatrix(np.arange(10, dtype=float)) m2 = DenseMatrix(np.ones(shape=(10, 2), dtype=float)) res = SplitMatrix([m1, m2]) assert res.shape == (10, 3) @pytest.mark.parametrize("n_rows", [5, 10, 25]) def test_matvec(n_rows): np.random.seed(1234) n_cols = 2 categories = [f"cat_{val}" for val in range(5)] X = pd.DataFrame(np.random.choice(categories, size=(n_rows, n_cols))).astype( "category" ) mat = from_pandas(X, cat_threshold=0) np.testing.assert_allclose(mat.matvec(np.array(mat.shape[1] * [1])), n_cols)
tests/test_split_matrix.py
from typing import List, Optional, Union import numpy as np import pandas as pd import pytest import scipy.sparse as sps import tabmat as tm from tabmat import from_pandas from tabmat.constructor import _split_sparse_and_dense_parts from tabmat.dense_matrix import DenseMatrix from tabmat.ext.sparse import csr_dense_sandwich from tabmat.split_matrix import SplitMatrix N = 100 def make_X() -> np.ndarray: X = np.zeros((N, 4)) X[:, 0] = 1.0 X[:10, 1] = 0.5 X[-20:, 2] = 0.25 X[:, 3] = 2.0 return X @pytest.fixture def X() -> np.ndarray: return make_X() def test_csc_to_split(X: np.ndarray): for T, D, S in [(0.05, 4, 0), (0.1, 3, 1), (0.2, 2, 2), (0.3, 2, 2), (1.0, 0, 4)]: dense, sparse, dense_ix, sparse_ix = _split_sparse_and_dense_parts( sps.csc_matrix(X), T ) fully_dense = SplitMatrix([dense, sparse], [dense_ix, sparse_ix]) if S == 0: assert fully_dense.indices[0].shape[0] == D assert len(fully_dense.indices) == 1 elif D == 0: assert fully_dense.indices[0].shape[0] == S assert len(fully_dense.indices) == 1 else: assert fully_dense.indices[0].shape[0] == D assert fully_dense.indices[1].shape[0] == S def split_mat() -> SplitMatrix: X = make_X() threshold = 0.1 cat_mat = tm.CategoricalMatrix(np.random.choice(range(4), X.shape[0])) dense, sparse, dense_ix, sparse_ix = _split_sparse_and_dense_parts( sps.csc_matrix(X), threshold ) cat_start = 1 + max(dense_ix.max(), sparse_ix.max()) mat = SplitMatrix( [dense, sparse, cat_mat], [dense_ix, sparse_ix, range(cat_start, cat_start + cat_mat.shape[1])], ) return mat def get_split_with_cat_components() -> List[ Union[tm.SparseMatrix, tm.DenseMatrix, tm.CategoricalMatrix] ]: n_rows = 10 np.random.seed(0) dense_1 = tm.DenseMatrix(np.random.random((n_rows, 3))) sparse_1 = tm.SparseMatrix(sps.random(n_rows, 3).tocsc()) cat = tm.CategoricalMatrix(np.random.choice(range(3), n_rows)) dense_2 = tm.DenseMatrix(np.random.random((n_rows, 3))) sparse_2 = tm.SparseMatrix(sps.random(n_rows, 3, density=0.5).tocsc()) cat_2 = tm.CategoricalMatrix(np.random.choice(range(3), n_rows), drop_first=True) return [dense_1, sparse_1, cat, dense_2, sparse_2, cat_2] def split_with_cat() -> SplitMatrix: """Initialized with multiple sparse and dense parts and no indices.""" return tm.SplitMatrix(get_split_with_cat_components()) def split_with_cat_64() -> SplitMatrix: mat = tm.SplitMatrix(get_split_with_cat_components()) matrices = mat.matrices for i, mat_ in enumerate(mat.matrices): if isinstance(mat_, tm.SparseMatrix): matrices[i] = tm.SparseMatrix( ( mat_.data, mat_.indices.astype(np.int64), mat_.indptr.astype(np.int64), ), shape=mat_.shape, ) elif isinstance(mat_, tm.DenseMatrix): matrices[i] = mat_.astype(np.float64) return tm.SplitMatrix(matrices, mat.indices) @pytest.mark.parametrize("mat", [split_with_cat(), split_with_cat_64()]) def test_init(mat: SplitMatrix): assert len(mat.indices) == 4 assert len(mat.matrices) == 4 assert (mat.indices[0] == np.concatenate([np.arange(3), np.arange(9, 12)])).all() assert mat.matrices[0].shape == (10, 6) assert mat.matrices[1].shape == (10, 6) assert mat.matrices[2].shape == (10, 3) def test_init_unsorted_indices(): dense = tm.DenseMatrix(np.random.random((10, 3))) with pytest.raises(ValueError): tm.SplitMatrix([dense], [[1, 0, 2]]) @pytest.mark.parametrize( "Acols", [np.arange(2, dtype=np.int32), np.array([1], dtype=np.int32)] ) @pytest.mark.parametrize( "Bcols", [ np.arange(4, dtype=np.int32), np.array([1], dtype=np.int32), np.array([1, 3], dtype=np.int32), ], ) def test_sandwich_sparse_dense(X: np.ndarray, Acols, Bcols): np.random.seed(0) n, k = X.shape d = np.random.random((n,)) A = sps.random(n, 2).tocsr() rows = np.arange(d.shape[0], dtype=np.int32) result = csr_dense_sandwich(A, X, d, rows, Acols, Bcols) expected = A.T.A[Acols, :] @ np.diag(d) @ X[:, Bcols] np.testing.assert_allclose(result, expected) # TODO: ensure cols are in order @pytest.mark.parametrize("mat", [split_mat(), split_with_cat(), split_with_cat_64()]) @pytest.mark.parametrize( "cols", [None, [0], [1, 2, 3], [1, 5]], ) def test_sandwich(mat: tm.SplitMatrix, cols): for _ in range(10): v = np.random.rand(mat.shape[0]) y1 = mat.sandwich(v, cols=cols) mat_limited = mat.A if cols is None else mat.A[:, cols] y2 = (mat_limited.T * v[None, :]) @ mat_limited np.testing.assert_allclose(y1, y2, atol=1e-12) @pytest.mark.parametrize("mat", [split_mat(), split_with_cat(), split_with_cat_64()]) @pytest.mark.parametrize("cols", [None, [0], [1, 2, 3], [1, 5]]) def test_split_col_subsets(mat: tm.SplitMatrix, cols): subset_cols_indices, subset_cols, n_cols = mat._split_col_subsets(cols) n_cols_correct = mat.shape[1] if cols is None else len(cols) def _get_lengths(vec_list: List[Optional[np.ndarray]]): return ( mat_.shape[1] if v is None else len(v) for v, mat_ in zip(vec_list, mat.matrices) ) assert n_cols == n_cols_correct assert sum(_get_lengths(subset_cols_indices)) == n_cols assert sum(_get_lengths(subset_cols)) == n_cols if cols is not None: cols = np.asarray(cols) for i in range(len(mat.indices)): if cols is not None: assert ( mat.indices[i][subset_cols[i]] == cols[subset_cols_indices[i]] ).all() else: assert subset_cols[i] is None assert (mat.indices[i] == subset_cols_indices[i]).all() def random_split_matrix(seed=0, n_rows=10, n_cols_per=3): if seed is not None: np.random.seed(seed) dense_1 = tm.DenseMatrix(np.random.random((n_rows, n_cols_per))) sparse = tm.SparseMatrix(sps.random(n_rows, n_cols_per).tocsc()) cat = tm.CategoricalMatrix(np.random.choice(range(n_cols_per), n_rows)) dense_2 = tm.DenseMatrix(np.random.random((n_rows, n_cols_per))) cat_2 = tm.CategoricalMatrix(np.random.choice(range(n_cols_per), n_rows)) mat = tm.SplitMatrix([dense_1, sparse, cat, dense_2, cat_2]) return mat def many_random_tests(checker): for i in range(10): mat = random_split_matrix( seed=(1 if i == 0 else None), n_rows=np.random.randint(130), n_cols_per=1 + np.random.randint(10), ) checker(mat) def test_sandwich_many_types(): def check(mat): d = np.random.random(mat.shape[0]) res = mat.sandwich(d) expected = (mat.A.T * d[None, :]) @ mat.A np.testing.assert_allclose(res, expected) many_random_tests(check) def test_transpose_matvec_many_types(): def check(mat): d = np.random.random(mat.shape[0]) res = mat.transpose_matvec(d) expected = mat.A.T.dot(d) np.testing.assert_almost_equal(res, expected) many_random_tests(check) def test_matvec_many_types(): def check(mat): d = np.random.random(mat.shape[1]) res = mat.matvec(d) expected = mat.A.dot(d) np.testing.assert_almost_equal(res, expected) many_random_tests(check) def test_init_from_1d(): m1 = DenseMatrix(np.arange(10, dtype=float)) m2 = DenseMatrix(np.ones(shape=(10, 2), dtype=float)) res = SplitMatrix([m1, m2]) assert res.shape == (10, 3) @pytest.mark.parametrize("n_rows", [5, 10, 25]) def test_matvec(n_rows): np.random.seed(1234) n_cols = 2 categories = [f"cat_{val}" for val in range(5)] X = pd.DataFrame(np.random.choice(categories, size=(n_rows, n_cols))).astype( "category" ) mat = from_pandas(X, cat_threshold=0) np.testing.assert_allclose(mat.matvec(np.array(mat.shape[1] * [1])), n_cols)
0.777215
0.729086
from utils.env import EnvStore import os import json import pymqi import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # function to establish connection to MQ Queue Manager def connect(): logger.info('Establising Connection with MQ Server') try: cd = None if not EnvStore.ccdtCheck(): logger.info('CCDT URL export is not set, will be using json envrionment client connections settings') cd = pymqi.CD(Version=pymqi.CMQXC.MQCD_VERSION_11) cd.ChannelName = MQDetails[EnvStore.CHANNEL] cd.ConnectionName = conn_info cd.ChannelType = pymqi.CMQC.MQCHT_CLNTCONN cd.TransportType = pymqi.CMQC.MQXPT_TCP logger.info('Checking Cypher details') # If a cipher is set then set the TLS settings if MQDetails[EnvStore.CIPHER]: logger.info('Making use of Cypher details') cd.SSLCipherSpec = MQDetails[EnvStore.CIPHER] # Key repository is not specified in CCDT so look in envrionment settings # Create an empty SCO object sco = pymqi.SCO() if MQDetails[EnvStore.KEY_REPOSITORY]: logger.info('Setting Key repository') sco.KeyRepository = MQDetails[EnvStore.KEY_REPOSITORY] #options = pymqi.CMQC.MQPMO_NO_SYNCPOINT | pymqi.CMQC.MQPMO_NEW_MSG_ID | pymqi.CMQC.MQPMO_NEW_CORREL_ID options = pymqi.CMQC.MQPMO_NEW_CORREL_ID qmgr = pymqi.QueueManager(None) qmgr.connect_with_options(MQDetails[EnvStore.QMGR], user=credentials[EnvStore.USER], password=credentials[EnvStore.PASSWORD], opts=options, cd=cd, sco=sco) return qmgr except pymqi.MQMIError as e: logger.error("Error connecting") logger.error(e) return None # function to establish connection to Topic def getSubscription(): logger.info('Connecting to Subscription') try: sub_desc = pymqi.SD() sub_desc["Options"] = pymqi.CMQC.MQSO_CREATE + pymqi.CMQC.MQSO_RESUME + \ pymqi.CMQC.MQSO_DURABLE + pymqi.CMQC.MQSO_MANAGED sub_desc.set_vs("SubName", "MySub") sub_desc.set_vs("ObjectString", MQDetails[EnvStore.TOPIC_NAME]) sub = pymqi.Subscription(qmgr) sub.sub(sub_desc=sub_desc) return sub except pymqi.MQMIError as e: logger.error("Error getting queue") logger.error(e) return None # function to get messages from subscription def getMessages(): logger.info('Attempting gets from Subscription') subOptions = pymqi.CMQC.MQGMO_NO_SYNCPOINT + \ pymqi.CMQC.MQGMO_FAIL_IF_QUIESCING + \ pymqi.CMQC.MQGMO_WAIT + \ pymqi.CMQC.MQGMO_NO_PROPERTIES gmo = pymqi.GMO(Options=subOptions) gmo["WaitInterval"] = 30 * 1000 # Message Descriptor md = pymqi.MD() keep_running = True while keep_running: try: # Reset the MsgId, CorrelId & GroupId so that we can reuse # the same 'md' object again. md.MsgId = pymqi.CMQC.MQMI_NONE md.CorrelId = pymqi.CMQC.MQCI_NONE md.GroupId = pymqi.CMQC.MQGI_NONE #message = subscription.get(None, pymqi.md(), gmo) message = subscription.get(None, md, gmo) # Process the message here.. msgObject = json.loads(message.decode()) logger.info('Have message from Queue') logger.info(msgObject) except pymqi.MQMIError as e: if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE: # No messages, that's OK, we can ignore it. pass else: # Some other error condition. raise except (UnicodeDecodeError, ValueError) as e: logger.info('Message is not valid json') logger.info(e) logger.info(message) continue except KeyboardInterrupt: logger.info('Have received a keyboard interrupt') keep_running = False def buildMQDetails(): for key in [EnvStore.QMGR, EnvStore.TOPIC_NAME, EnvStore.CHANNEL, EnvStore.HOST, EnvStore.PORT, EnvStore.KEY_REPOSITORY, EnvStore.CIPHER]: MQDetails[key] = EnvStore.getEnvValue(key) # Application Logic starts here logger.info("Application is Starting") envStore = EnvStore() envStore.setEnv() MQDetails = {} credentials = { EnvStore.USER: EnvStore.getEnvValue(EnvStore.APP_USER), EnvStore.PASSWORD: EnvStore.getEnvValue(EnvStore.APP_PASSWORD) } buildMQDetails() logger.info('Credentials are set') #logger.info(credentials) #conn_info = "%s(%s)" % (MQDetails[EnvStore.HOST], MQDetails[EnvStore.PORT]) conn_info = EnvStore.getConnection(EnvStore.HOST, EnvStore.PORT) qmgr = None subscription = None qmgr = connect() if (qmgr): subscription = getSubscription() if (subscription): getMessages() subscription.close( sub_close_options=pymqi.CMQC.MQCO_KEEP_SUB, close_sub_queue=True) if (qmgr): qmgr.disconnect() logger.info("Application is closing")
Python/basicsubscribe.py
from utils.env import EnvStore import os import json import pymqi import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # function to establish connection to MQ Queue Manager def connect(): logger.info('Establising Connection with MQ Server') try: cd = None if not EnvStore.ccdtCheck(): logger.info('CCDT URL export is not set, will be using json envrionment client connections settings') cd = pymqi.CD(Version=pymqi.CMQXC.MQCD_VERSION_11) cd.ChannelName = MQDetails[EnvStore.CHANNEL] cd.ConnectionName = conn_info cd.ChannelType = pymqi.CMQC.MQCHT_CLNTCONN cd.TransportType = pymqi.CMQC.MQXPT_TCP logger.info('Checking Cypher details') # If a cipher is set then set the TLS settings if MQDetails[EnvStore.CIPHER]: logger.info('Making use of Cypher details') cd.SSLCipherSpec = MQDetails[EnvStore.CIPHER] # Key repository is not specified in CCDT so look in envrionment settings # Create an empty SCO object sco = pymqi.SCO() if MQDetails[EnvStore.KEY_REPOSITORY]: logger.info('Setting Key repository') sco.KeyRepository = MQDetails[EnvStore.KEY_REPOSITORY] #options = pymqi.CMQC.MQPMO_NO_SYNCPOINT | pymqi.CMQC.MQPMO_NEW_MSG_ID | pymqi.CMQC.MQPMO_NEW_CORREL_ID options = pymqi.CMQC.MQPMO_NEW_CORREL_ID qmgr = pymqi.QueueManager(None) qmgr.connect_with_options(MQDetails[EnvStore.QMGR], user=credentials[EnvStore.USER], password=credentials[EnvStore.PASSWORD], opts=options, cd=cd, sco=sco) return qmgr except pymqi.MQMIError as e: logger.error("Error connecting") logger.error(e) return None # function to establish connection to Topic def getSubscription(): logger.info('Connecting to Subscription') try: sub_desc = pymqi.SD() sub_desc["Options"] = pymqi.CMQC.MQSO_CREATE + pymqi.CMQC.MQSO_RESUME + \ pymqi.CMQC.MQSO_DURABLE + pymqi.CMQC.MQSO_MANAGED sub_desc.set_vs("SubName", "MySub") sub_desc.set_vs("ObjectString", MQDetails[EnvStore.TOPIC_NAME]) sub = pymqi.Subscription(qmgr) sub.sub(sub_desc=sub_desc) return sub except pymqi.MQMIError as e: logger.error("Error getting queue") logger.error(e) return None # function to get messages from subscription def getMessages(): logger.info('Attempting gets from Subscription') subOptions = pymqi.CMQC.MQGMO_NO_SYNCPOINT + \ pymqi.CMQC.MQGMO_FAIL_IF_QUIESCING + \ pymqi.CMQC.MQGMO_WAIT + \ pymqi.CMQC.MQGMO_NO_PROPERTIES gmo = pymqi.GMO(Options=subOptions) gmo["WaitInterval"] = 30 * 1000 # Message Descriptor md = pymqi.MD() keep_running = True while keep_running: try: # Reset the MsgId, CorrelId & GroupId so that we can reuse # the same 'md' object again. md.MsgId = pymqi.CMQC.MQMI_NONE md.CorrelId = pymqi.CMQC.MQCI_NONE md.GroupId = pymqi.CMQC.MQGI_NONE #message = subscription.get(None, pymqi.md(), gmo) message = subscription.get(None, md, gmo) # Process the message here.. msgObject = json.loads(message.decode()) logger.info('Have message from Queue') logger.info(msgObject) except pymqi.MQMIError as e: if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE: # No messages, that's OK, we can ignore it. pass else: # Some other error condition. raise except (UnicodeDecodeError, ValueError) as e: logger.info('Message is not valid json') logger.info(e) logger.info(message) continue except KeyboardInterrupt: logger.info('Have received a keyboard interrupt') keep_running = False def buildMQDetails(): for key in [EnvStore.QMGR, EnvStore.TOPIC_NAME, EnvStore.CHANNEL, EnvStore.HOST, EnvStore.PORT, EnvStore.KEY_REPOSITORY, EnvStore.CIPHER]: MQDetails[key] = EnvStore.getEnvValue(key) # Application Logic starts here logger.info("Application is Starting") envStore = EnvStore() envStore.setEnv() MQDetails = {} credentials = { EnvStore.USER: EnvStore.getEnvValue(EnvStore.APP_USER), EnvStore.PASSWORD: EnvStore.getEnvValue(EnvStore.APP_PASSWORD) } buildMQDetails() logger.info('Credentials are set') #logger.info(credentials) #conn_info = "%s(%s)" % (MQDetails[EnvStore.HOST], MQDetails[EnvStore.PORT]) conn_info = EnvStore.getConnection(EnvStore.HOST, EnvStore.PORT) qmgr = None subscription = None qmgr = connect() if (qmgr): subscription = getSubscription() if (subscription): getMessages() subscription.close( sub_close_options=pymqi.CMQC.MQCO_KEEP_SUB, close_sub_queue=True) if (qmgr): qmgr.disconnect() logger.info("Application is closing")
0.373876
0.079353
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course_name', models.CharField(max_length=200)), ('course_description', models.CharField(max_length=200)), ('course_created_datetime', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('instructor', models.BooleanField(default=False)), ('user_created_datetime', models.DateTimeField(auto_now_add=True)), ('user_updated_datetime', models.DateTimeField(auto_now=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Test', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('test_title', models.CharField(max_length=200)), ('test_description', models.CharField(max_length=200)), ('test_due_date', models.DateField()), ('content_created_datetime', models.DateTimeField(auto_now_add=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ], ), migrations.CreateModel( name='Content', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content_title', models.CharField(max_length=200)), ('content_description', models.CharField(max_length=200)), ('content_created_datetime', models.DateTimeField(auto_now_add=True)), ('content_updated_datetime', models.DateTimeField(auto_now=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ], ), ]
courses/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course_name', models.CharField(max_length=200)), ('course_description', models.CharField(max_length=200)), ('course_created_datetime', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('instructor', models.BooleanField(default=False)), ('user_created_datetime', models.DateTimeField(auto_now_add=True)), ('user_updated_datetime', models.DateTimeField(auto_now=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Test', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('test_title', models.CharField(max_length=200)), ('test_description', models.CharField(max_length=200)), ('test_due_date', models.DateField()), ('content_created_datetime', models.DateTimeField(auto_now_add=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ], ), migrations.CreateModel( name='Content', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content_title', models.CharField(max_length=200)), ('content_description', models.CharField(max_length=200)), ('content_created_datetime', models.DateTimeField(auto_now_add=True)), ('content_updated_datetime', models.DateTimeField(auto_now=True)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.course')), ], ), ]
0.551574
0.150903
__author__ = "<NAME>" __email__ = "schmidt89 at informatik.uni-marburg.de" from androlyze.log.Log import log from androlyze.storage.exception import StorageException class ImportStorageInterface: ''' Interface for the import storage ''' def create_entry_for_apk(self, apk, update = False, tag = None): ''' Create an entry for the `apk`. Will also update the path, if the file is already present in the database and has the same hash (at least if `update`). Parameters ---------- apk : Apk update : bool, optional (default is False) Update an `apk` that has already been imported. tag : str, optional (default is None) Tag the apk with some text. Raises ------ StorageException ''' raise NotImplementedError def create_entry_for_apks(self, apks, update, tag = None): ''' Create entry for the `apks`. Parameters ---------- apk: iterable<Apk> update : bool Update apks that have already been imported. tag : str, optional (default is None) Tag the apk with some text. ''' for apk in apks: try: self.create_entry_for_apk(apk, update, tag) except StorageException as e: log.warn(e) def delete_entry_for_apk(self, apk, delete_apk = False): ''' Delete the entry for `apk`. Parameters ---------- apk: Apk delete_apk : boolean, optional (default is False) If true, also delete the .apk file from the file system (but only if it is in the storage directory!). Raises ------ StorageException ''' raise NotImplementedError def contains(self, apk): ''' Check if the `apk` is present in the storage. Parameters ---------- apk: Apk Returns ------- bool ''' raise NotImplementedError
androlyze/storage/ImportStorageInterface.py
__author__ = "<NAME>" __email__ = "schmidt89 at informatik.uni-marburg.de" from androlyze.log.Log import log from androlyze.storage.exception import StorageException class ImportStorageInterface: ''' Interface for the import storage ''' def create_entry_for_apk(self, apk, update = False, tag = None): ''' Create an entry for the `apk`. Will also update the path, if the file is already present in the database and has the same hash (at least if `update`). Parameters ---------- apk : Apk update : bool, optional (default is False) Update an `apk` that has already been imported. tag : str, optional (default is None) Tag the apk with some text. Raises ------ StorageException ''' raise NotImplementedError def create_entry_for_apks(self, apks, update, tag = None): ''' Create entry for the `apks`. Parameters ---------- apk: iterable<Apk> update : bool Update apks that have already been imported. tag : str, optional (default is None) Tag the apk with some text. ''' for apk in apks: try: self.create_entry_for_apk(apk, update, tag) except StorageException as e: log.warn(e) def delete_entry_for_apk(self, apk, delete_apk = False): ''' Delete the entry for `apk`. Parameters ---------- apk: Apk delete_apk : boolean, optional (default is False) If true, also delete the .apk file from the file system (but only if it is in the storage directory!). Raises ------ StorageException ''' raise NotImplementedError def contains(self, apk): ''' Check if the `apk` is present in the storage. Parameters ---------- apk: Apk Returns ------- bool ''' raise NotImplementedError
0.63409
0.253185
from git import Repo, db import os.path import re import sys import glob from parser_java_kotlin import Parser from pathlib import Path from tqdm import tqdm class ChangedMethodsFinder: file_extension = {'java': '.*.java', 'kotlin':'.*.kt'} def __init__(self, path='.'): self.repo = None self.path = path self.code_a = '' self.code_b = '' def collect_code_from_commit(self, diff_file, commit_step): try: return self.repo.git.show('{}:{}'.format(commit_step, diff_file)).split('\n') except Exception: return['error'] def is_match_lang_ext(self, filename): return (re.match(self.file_extension['java'], filename) or re.match(self.file_extension['kotlin'], filename)) def collect_modified_files_last_two_commits(self, commits = ["HEAD", "HEAD~1"]): commit_dev = self.repo.commit(commits[0]) commit_origin_dev = self.repo.commit(commits[1]) diff_index = commit_origin_dev.diff(commit_dev) diff_files = [] for diff_item in diff_index.iter_change_type('M'): diff_files.append(diff_item.b_path) if len(diff_files) > 20: return [] diff_files = [f for f in diff_files if self.is_match_lang_ext(f) and not re.search('auto_generated', f)] return diff_files def remove_tabs(self, code): code = list(filter(lambda x: not (x.strip()[:2] == '//'), code)) code = '\n'.join(code) code = re.sub(' +', ' ', code) return re.sub('\t+', '', code) def open_repo(self, path='.'): try: self.repo = Repo(path, odbt=db.GitDB) except Exception: print("Check path to repository. Maybe, you should write path in double quotes\"\"") def code_fragment(self, bounds, code): if not bounds: return '' if bounds[1]<= bounds[0]: return '' return ''.join(code)[bounds[0]: bounds[1]] def get_method_info(self, ast): methods_info = ast.get_method_names_and_bounds() methods_info = dict(methods_info) return methods_info def compare_ast(self, ast_a, ast_b, diff_file): methods_info_a = self.get_method_info(ast_a) methods_info_b = self.get_method_info(ast_b) all_methods = list(methods_info_a.keys()) + list(methods_info_b.keys()) changed_methods = set() for method in all_methods: if method in methods_info_a and method in methods_info_b: method_code_a = self.code_fragment(methods_info_a[method][0], self.codes_a[diff_file]) method_code_b = self.code_fragment(methods_info_b[method][0], self.codes_b[diff_file]) if method_code_a != method_code_b: changed_methods.add((method, methods_info_a[method][1])) if method in methods_info_a and not (method in methods_info_b): changed_methods.add((method, methods_info_a[method][1])) return changed_methods def get_code(self, diff_file, commit): code = self.collect_code_from_commit(diff_file, commit) code = self.remove_tabs(code) return code def construct_ast(self, code, language='java', diff_file=''): parser = Parser(language) ast = parser.parse(code, diff_file) return ast def find_changed_methods_by_language(self, language='java', diff_files=[], commits=["HEAD", "HEAD~1"]): self.trees_a, self.trees_b = dict(), dict() self.codes_a, self.codes_b = dict(), dict() all_changed_methods = set() for diff_file in diff_files: self.codes_a[diff_file] = self.get_code(diff_file, commits[0]) self.codes_b[diff_file] = self.get_code(diff_file, commits[1]) self.trees_a[diff_file] = self.construct_ast(self.codes_a[diff_file], language, diff_file) self.trees_b[diff_file] = self.construct_ast(self.codes_b[diff_file], language, diff_file) all_changed_methods = all_changed_methods.union(self.compare_ast(self.trees_a[diff_file], self.trees_b[diff_file], diff_file)) return all_changed_methods def find_changed_methods(self, path='.', commits = ["HEAD", "HEAD~1"]): self.open_repo(path) diff_files = self.collect_modified_files_last_two_commits(commits) java_changed_methods = self.find_changed_methods_by_language('java', diff_files, commits) kotlin_changed_methods = self.find_changed_methods_by_language('kotlin', diff_files, commits) return java_changed_methods.union(kotlin_changed_methods) if __name__ == "__main__": path = '.' if len(sys.argv) > 1: path = sys.argv[1] cmf = ChangedMethodsFinder() commits = ['ecdd37cc44f9beb6870c78c3432b1fddcdab8292~1','ecdd37cc44f9beb6870c78c3432b1fddcdab8292'] print(cmf.find_changed_methods(path, commits))
data_aggregation/get_java_methods.py
from git import Repo, db import os.path import re import sys import glob from parser_java_kotlin import Parser from pathlib import Path from tqdm import tqdm class ChangedMethodsFinder: file_extension = {'java': '.*.java', 'kotlin':'.*.kt'} def __init__(self, path='.'): self.repo = None self.path = path self.code_a = '' self.code_b = '' def collect_code_from_commit(self, diff_file, commit_step): try: return self.repo.git.show('{}:{}'.format(commit_step, diff_file)).split('\n') except Exception: return['error'] def is_match_lang_ext(self, filename): return (re.match(self.file_extension['java'], filename) or re.match(self.file_extension['kotlin'], filename)) def collect_modified_files_last_two_commits(self, commits = ["HEAD", "HEAD~1"]): commit_dev = self.repo.commit(commits[0]) commit_origin_dev = self.repo.commit(commits[1]) diff_index = commit_origin_dev.diff(commit_dev) diff_files = [] for diff_item in diff_index.iter_change_type('M'): diff_files.append(diff_item.b_path) if len(diff_files) > 20: return [] diff_files = [f for f in diff_files if self.is_match_lang_ext(f) and not re.search('auto_generated', f)] return diff_files def remove_tabs(self, code): code = list(filter(lambda x: not (x.strip()[:2] == '//'), code)) code = '\n'.join(code) code = re.sub(' +', ' ', code) return re.sub('\t+', '', code) def open_repo(self, path='.'): try: self.repo = Repo(path, odbt=db.GitDB) except Exception: print("Check path to repository. Maybe, you should write path in double quotes\"\"") def code_fragment(self, bounds, code): if not bounds: return '' if bounds[1]<= bounds[0]: return '' return ''.join(code)[bounds[0]: bounds[1]] def get_method_info(self, ast): methods_info = ast.get_method_names_and_bounds() methods_info = dict(methods_info) return methods_info def compare_ast(self, ast_a, ast_b, diff_file): methods_info_a = self.get_method_info(ast_a) methods_info_b = self.get_method_info(ast_b) all_methods = list(methods_info_a.keys()) + list(methods_info_b.keys()) changed_methods = set() for method in all_methods: if method in methods_info_a and method in methods_info_b: method_code_a = self.code_fragment(methods_info_a[method][0], self.codes_a[diff_file]) method_code_b = self.code_fragment(methods_info_b[method][0], self.codes_b[diff_file]) if method_code_a != method_code_b: changed_methods.add((method, methods_info_a[method][1])) if method in methods_info_a and not (method in methods_info_b): changed_methods.add((method, methods_info_a[method][1])) return changed_methods def get_code(self, diff_file, commit): code = self.collect_code_from_commit(diff_file, commit) code = self.remove_tabs(code) return code def construct_ast(self, code, language='java', diff_file=''): parser = Parser(language) ast = parser.parse(code, diff_file) return ast def find_changed_methods_by_language(self, language='java', diff_files=[], commits=["HEAD", "HEAD~1"]): self.trees_a, self.trees_b = dict(), dict() self.codes_a, self.codes_b = dict(), dict() all_changed_methods = set() for diff_file in diff_files: self.codes_a[diff_file] = self.get_code(diff_file, commits[0]) self.codes_b[diff_file] = self.get_code(diff_file, commits[1]) self.trees_a[diff_file] = self.construct_ast(self.codes_a[diff_file], language, diff_file) self.trees_b[diff_file] = self.construct_ast(self.codes_b[diff_file], language, diff_file) all_changed_methods = all_changed_methods.union(self.compare_ast(self.trees_a[diff_file], self.trees_b[diff_file], diff_file)) return all_changed_methods def find_changed_methods(self, path='.', commits = ["HEAD", "HEAD~1"]): self.open_repo(path) diff_files = self.collect_modified_files_last_two_commits(commits) java_changed_methods = self.find_changed_methods_by_language('java', diff_files, commits) kotlin_changed_methods = self.find_changed_methods_by_language('kotlin', diff_files, commits) return java_changed_methods.union(kotlin_changed_methods) if __name__ == "__main__": path = '.' if len(sys.argv) > 1: path = sys.argv[1] cmf = ChangedMethodsFinder() commits = ['ecdd37cc44f9beb6870c78c3432b1fddcdab8292~1','ecdd37cc44f9beb6870c78c3432b1fddcdab8292'] print(cmf.find_changed_methods(path, commits))
0.233794
0.137851
from webparser.youtube import api from django.db import transaction from django.utils import timezone from . import models from core import models as core_models def video__get(youtube_id): try: return models.Video.objects.get(youtube_id = youtube_id) except models.Video.DoesNotExist: return None def channel__get_or_create(youtube_id, title): obj, create = models.Channel.objects.get_or_create( youtube_id = youtube_id, defaults = { 'title': title, } ) return obj def search(query, limit): timestamp = timezone.now() videos_id = api.search(query, limit) with transaction.atomic(): search = models.Search.objects.create( query = query, timestamp = timestamp, ) for index, video_id in enumerate(videos_id): try: if not video__get(video_id): rank = index + 1 d = api.get_video_info(video_id) channel = channel__get_or_create(d['user_id'], d['user_username']) video = models.Video.objects.create( youtube_id = video_id, title = d['title'], publish_date = d['publish_date'], channel = channel, category = d['category'], license = d['license'], view_count = d['view_count'], likes = d['likes'], dislikes = d['dislikes'], description_text = d['description_text'], description_html = d['description_html'], url = core_models.URL.objects.create( url = d['_url'], timestamp = timestamp, content = d['_response_obj'].html.html ) ) models.VideoSearch.objects.create( video_id = video, search_id = search, rank = rank, ) except Exception: print('Video ID: {}'.format(video_id)) raise
httpserver/youtube/api.py
from webparser.youtube import api from django.db import transaction from django.utils import timezone from . import models from core import models as core_models def video__get(youtube_id): try: return models.Video.objects.get(youtube_id = youtube_id) except models.Video.DoesNotExist: return None def channel__get_or_create(youtube_id, title): obj, create = models.Channel.objects.get_or_create( youtube_id = youtube_id, defaults = { 'title': title, } ) return obj def search(query, limit): timestamp = timezone.now() videos_id = api.search(query, limit) with transaction.atomic(): search = models.Search.objects.create( query = query, timestamp = timestamp, ) for index, video_id in enumerate(videos_id): try: if not video__get(video_id): rank = index + 1 d = api.get_video_info(video_id) channel = channel__get_or_create(d['user_id'], d['user_username']) video = models.Video.objects.create( youtube_id = video_id, title = d['title'], publish_date = d['publish_date'], channel = channel, category = d['category'], license = d['license'], view_count = d['view_count'], likes = d['likes'], dislikes = d['dislikes'], description_text = d['description_text'], description_html = d['description_html'], url = core_models.URL.objects.create( url = d['_url'], timestamp = timestamp, content = d['_response_obj'].html.html ) ) models.VideoSearch.objects.create( video_id = video, search_id = search, rank = rank, ) except Exception: print('Video ID: {}'.format(video_id)) raise
0.375477
0.089415
from __future__ import print_function # ------------------------------------------------------------------------------------------------ # Copyright (c) 2016 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ------------------------------------------------------------------------------------------------ # Tutorial sample #1: Run simple mission from builtins import range import MalmoPython from past.utils import old_div import os import sys import time import json import tkinter as tk import math CANVAS_WIDTH = 390 CANVAS_HEIGHT = 540 ZERO_X = 11 ZERO_Y = -2 visited_list = [] def blockX(x): act_x = math.floor(ZERO_X - x) return act_x * 30 def blockY(y): act_y = math.floor(y) - ZERO_Y return (CANVAS_HEIGHT - act_y * 30) - 30 root = tk.Tk() root.wm_title("Agent Tracker") canvas = tk.Canvas(root, width=CANVAS_WIDTH, height=CANVAS_HEIGHT, borderwidth=0, highlightthickness=0, bg="black") canvas.pack() root.update() def updateBlocks(xpos, ypos, stone): canvas.delete('all') if stone: current_block = (blockX(xpos), blockY(ypos), blockX(xpos)+30, blockY(ypos)+30) if current_block not in visited_list: visited_list.append(current_block) for block in visited_list: canvas.create_rectangle(block[0], block[1], block[2], block[3], fill="grey") canvas.create_rectangle(180, 420, 210, 450, fill="yellow") canvas.create_rectangle(180, 90, 210, 120, fill="blue") real_x = (ZERO_X - x) * 30 real_y = (CANVAS_HEIGHT - (y - ZERO_Y) * 30) canvas.create_oval(real_x - 10, real_y - 10, real_x + 10, real_y + 10, fill="red") #print("Block at: ", blockX(xpos), blockY(ypos), blockX(xpos)+30, blockY(ypos)+30) root.update() if sys.version_info[0] == 2: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately else: import functools print = functools.partial(print, flush=True) # Create default Malmo objects: agent_host = MalmoPython.AgentHost() try: agent_host.parse( sys.argv ) except RuntimeError as e: print('ERROR:',e) print(agent_host.getUsage()) exit(1) if agent_host.receivedArgument("help"): print(agent_host.getUsage()) exit(0) mission_file = './bridging.xml' with open(mission_file, 'r') as f: print("Loading mission from %s" % mission_file) mission_xml = f.read() my_mission = MalmoPython.MissionSpec(mission_xml, True) my_mission_record = MalmoPython.MissionRecordSpec() # Attempt to start a mission: max_retries = 3 for retry in range(max_retries): try: agent_host.startMission( my_mission, my_mission_record ) break except RuntimeError as e: if retry == max_retries - 1: print("Error starting mission:",e) exit(1) else: time.sleep(2) # Loop until mission starts: print("Waiting for the mission to start ", end=' ') world_state = agent_host.getWorldState() while not world_state.has_mission_begun: print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() for error in world_state.errors: print("Error:",error.text) print() print("Mission running ", end=' ') # Loop until mission ends: while world_state.is_mission_running: print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() if world_state.number_of_observations_since_last_state > 0: # Have any observations come in? msg = world_state.observations[-1].text # Yes, so get the text observations = json.loads(msg) # and parse the JSON grid = observations['floor3x3'] distance = observations['distanceFromend'] x = observations["XPos"] y = observations["ZPos"] updateBlocks(x, y, grid[4]=="stone") #print(distance) #print(grid) for error in world_state.errors: print("Error:",error.text) print() print("Mission ended") # Mission has ended.
Python_Examples/bridging.py
from __future__ import print_function # ------------------------------------------------------------------------------------------------ # Copyright (c) 2016 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ------------------------------------------------------------------------------------------------ # Tutorial sample #1: Run simple mission from builtins import range import MalmoPython from past.utils import old_div import os import sys import time import json import tkinter as tk import math CANVAS_WIDTH = 390 CANVAS_HEIGHT = 540 ZERO_X = 11 ZERO_Y = -2 visited_list = [] def blockX(x): act_x = math.floor(ZERO_X - x) return act_x * 30 def blockY(y): act_y = math.floor(y) - ZERO_Y return (CANVAS_HEIGHT - act_y * 30) - 30 root = tk.Tk() root.wm_title("Agent Tracker") canvas = tk.Canvas(root, width=CANVAS_WIDTH, height=CANVAS_HEIGHT, borderwidth=0, highlightthickness=0, bg="black") canvas.pack() root.update() def updateBlocks(xpos, ypos, stone): canvas.delete('all') if stone: current_block = (blockX(xpos), blockY(ypos), blockX(xpos)+30, blockY(ypos)+30) if current_block not in visited_list: visited_list.append(current_block) for block in visited_list: canvas.create_rectangle(block[0], block[1], block[2], block[3], fill="grey") canvas.create_rectangle(180, 420, 210, 450, fill="yellow") canvas.create_rectangle(180, 90, 210, 120, fill="blue") real_x = (ZERO_X - x) * 30 real_y = (CANVAS_HEIGHT - (y - ZERO_Y) * 30) canvas.create_oval(real_x - 10, real_y - 10, real_x + 10, real_y + 10, fill="red") #print("Block at: ", blockX(xpos), blockY(ypos), blockX(xpos)+30, blockY(ypos)+30) root.update() if sys.version_info[0] == 2: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately else: import functools print = functools.partial(print, flush=True) # Create default Malmo objects: agent_host = MalmoPython.AgentHost() try: agent_host.parse( sys.argv ) except RuntimeError as e: print('ERROR:',e) print(agent_host.getUsage()) exit(1) if agent_host.receivedArgument("help"): print(agent_host.getUsage()) exit(0) mission_file = './bridging.xml' with open(mission_file, 'r') as f: print("Loading mission from %s" % mission_file) mission_xml = f.read() my_mission = MalmoPython.MissionSpec(mission_xml, True) my_mission_record = MalmoPython.MissionRecordSpec() # Attempt to start a mission: max_retries = 3 for retry in range(max_retries): try: agent_host.startMission( my_mission, my_mission_record ) break except RuntimeError as e: if retry == max_retries - 1: print("Error starting mission:",e) exit(1) else: time.sleep(2) # Loop until mission starts: print("Waiting for the mission to start ", end=' ') world_state = agent_host.getWorldState() while not world_state.has_mission_begun: print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() for error in world_state.errors: print("Error:",error.text) print() print("Mission running ", end=' ') # Loop until mission ends: while world_state.is_mission_running: print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() if world_state.number_of_observations_since_last_state > 0: # Have any observations come in? msg = world_state.observations[-1].text # Yes, so get the text observations = json.loads(msg) # and parse the JSON grid = observations['floor3x3'] distance = observations['distanceFromend'] x = observations["XPos"] y = observations["ZPos"] updateBlocks(x, y, grid[4]=="stone") #print(distance) #print(grid) for error in world_state.errors: print("Error:",error.text) print() print("Mission ended") # Mission has ended.
0.357007
0.162546
from __future__ import print_function import sys import time import Pyro4 import bench if sys.version_info < (3, 0): input = raw_input uri = input("Uri of benchmark server? ").strip() object = Pyro4.core.Proxy(uri) object._pyroBind() assert "oneway" in object._pyroOneway # make sure this method is indeed marked as @oneway def f1(): _ = object.length('<NAME> Jong') def f2(): _ = object.timestwo(21) def f3(): _ = object.bigreply() def f4(): _ = object.manyargs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) def f5(): _ = object.noreply(99993333) def f6(): _ = object.varargs('een', 2, (3,), [4]) def f7(): _ = object.keywords(arg1='zork') def f8(): _ = object.echo('een', 2, (3,), [4]) def f9(): _ = object.meth1('stringetje') def fa(): _ = object.meth2('stringetje') def fb(): _ = object.meth3('stringetje') def fc(): _ = object.meth4('stringetje') def fd(): _ = object.bigarg('Argument' * 50) def fe(): object.oneway('stringetje', 432423434, 9.8765432) def ff(): _ = object.mapping({"aap": 42, "noot": 99, "mies": 987654}) funcs = (f1, f2, f3, f4, f5, f6, f7, f8, f9, fa, fb, fc, fd, fe, ff) print('-------- BENCHMARK REMOTE OBJECT ---------') print('Pay attention to the "fe" test -- this is a Oneway call and should be *fast*') print('(if you are running the server and client on different machines)') begin = time.time() iters = 1000 for f in funcs: sys.stdout.write("%d times %s " % (iters, f.__name__)) voor = time.time() for i in range(iters): f() sys.stdout.write("%.3f\n" % (time.time() - voor)) sys.stdout.flush() duration = time.time() - begin print('total time %.3f seconds' % duration) amount = len(funcs) * iters print('total method calls: %d' % (amount)) avg_pyro_msec = 1000.0 * duration / amount print('avg. time per method call: %.3f msec (%d/sec) (serializer: %s)' % (avg_pyro_msec, amount / duration, Pyro4.config.SERIALIZER)) print('-------- BENCHMARK LOCAL OBJECT ---------') object = bench.bench() begin = time.time() iters = 200000 for f in funcs: sys.stdout.write("%d times %s " % (iters, f.__name__)) voor = time.time() for i in range(iters): f() sys.stdout.write("%.3f\n" % (time.time() - voor)) sys.stdout.flush() duration = time.time() - begin print('total time %.3f seconds' % duration) amount = len(funcs) * iters print('total method calls: %d' % (amount)) avg_normal_msec = 1000.0 * duration / amount print('avg. time per method call: %.3f msec (%d/sec)' % (avg_normal_msec, amount / duration // 1000 * 1000)) print('Normal method call is %.0f times faster than Pyro method call.' % (avg_pyro_msec / avg_normal_msec))
examples/benchmark/client.py
from __future__ import print_function import sys import time import Pyro4 import bench if sys.version_info < (3, 0): input = raw_input uri = input("Uri of benchmark server? ").strip() object = Pyro4.core.Proxy(uri) object._pyroBind() assert "oneway" in object._pyroOneway # make sure this method is indeed marked as @oneway def f1(): _ = object.length('<NAME> Jong') def f2(): _ = object.timestwo(21) def f3(): _ = object.bigreply() def f4(): _ = object.manyargs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) def f5(): _ = object.noreply(99993333) def f6(): _ = object.varargs('een', 2, (3,), [4]) def f7(): _ = object.keywords(arg1='zork') def f8(): _ = object.echo('een', 2, (3,), [4]) def f9(): _ = object.meth1('stringetje') def fa(): _ = object.meth2('stringetje') def fb(): _ = object.meth3('stringetje') def fc(): _ = object.meth4('stringetje') def fd(): _ = object.bigarg('Argument' * 50) def fe(): object.oneway('stringetje', 432423434, 9.8765432) def ff(): _ = object.mapping({"aap": 42, "noot": 99, "mies": 987654}) funcs = (f1, f2, f3, f4, f5, f6, f7, f8, f9, fa, fb, fc, fd, fe, ff) print('-------- BENCHMARK REMOTE OBJECT ---------') print('Pay attention to the "fe" test -- this is a Oneway call and should be *fast*') print('(if you are running the server and client on different machines)') begin = time.time() iters = 1000 for f in funcs: sys.stdout.write("%d times %s " % (iters, f.__name__)) voor = time.time() for i in range(iters): f() sys.stdout.write("%.3f\n" % (time.time() - voor)) sys.stdout.flush() duration = time.time() - begin print('total time %.3f seconds' % duration) amount = len(funcs) * iters print('total method calls: %d' % (amount)) avg_pyro_msec = 1000.0 * duration / amount print('avg. time per method call: %.3f msec (%d/sec) (serializer: %s)' % (avg_pyro_msec, amount / duration, Pyro4.config.SERIALIZER)) print('-------- BENCHMARK LOCAL OBJECT ---------') object = bench.bench() begin = time.time() iters = 200000 for f in funcs: sys.stdout.write("%d times %s " % (iters, f.__name__)) voor = time.time() for i in range(iters): f() sys.stdout.write("%.3f\n" % (time.time() - voor)) sys.stdout.flush() duration = time.time() - begin print('total time %.3f seconds' % duration) amount = len(funcs) * iters print('total method calls: %d' % (amount)) avg_normal_msec = 1000.0 * duration / amount print('avg. time per method call: %.3f msec (%d/sec)' % (avg_normal_msec, amount / duration // 1000 * 1000)) print('Normal method call is %.0f times faster than Pyro method call.' % (avg_pyro_msec / avg_normal_msec))
0.286568
0.128197